Jump to content
xisto Community
alfonzo

How Do I Create And Write To Files? creating, writing, deleting files

Recommended Posts

Hi,Can someone please tell me how to create files and write to them in PHP. I just want to create a simple file containing text, and then be able to read it or update it.ThanksAlfie

Share this post


Link to post
Share on other sites

Before you can write data into a file this should be existed:
Here is a sample code on how to read/write into a file.

Create a new php file then type this:

<?php$myFile = "test.txt";$filehandler = fopen($myFile, 'w') or die("can't open file");$stringData = "You're text here \r";fwrite($filehandler, $stringData);$stringData = "Another Text here \r";fwrite($filehandler, $stringData);fclose($filehandler );?>

Explanation:

Var $myFile on the first line declares the filename of you're file.If its on different directory please specify that directory where it is located.

The second line creates a variablle that will handle the file..That is why i called this file handler. fopen() is a function that will open that file. 'w' is for you to write..If you only want to read it just make it 'r'

$stringData variable is the string or character you want to write on the file plus a carriage return.

The fourth line will actually do the writing. fwrite() function.It takes two parameter the filehandler and the string you will write which is $stringData.

And everytime you open a file you will also need to close this using fclose() function.

Hope it helps.

Share this post


Link to post
Share on other sites
<?php$myFile = "test.txt";$filehandler = fopen($myFile, 'w') or die("can't open file");// this will create a new file if the file does not exist other wise overwrite it// to ensure that you dont overwrite an existing file but append to it use fopen($myFile, 'a')// if you want to read and write to the same file use w+/a+ mode to open the file$stringData = "You're text here \r";fwrite($filehandler, $stringData);$stringData = "Another Text here \r";fwrite($filehandler, $stringData);fclose($filehandler );?>

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×
×
  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.