Write to a file from PHP

Write To A File

From PHP you are able to open up a file on your server and write to it. If the file does not exist we can create it, however if the file already exists you must chmod it to 777 so it will be writable.

When writing to a file, the first thing you need to do is to open up the file. We do that with this code:

$File = "YourFile.txt";
$Handle = fopen($File, 'w');

Now we can use the fwrite command to add data to our file. We would do this as shown below:

$File = "YourFile.txt";
$Handle = fopen($File, 'w');
$Data = "Jane Doe\n";
fwrite($Handle, $Data);
$Data = "Bilbo Jones\n";
fwrite($Handle, $Data);
print "Data Written";

At the end of the file we use fclose to close the file we have been working with.


One thought on “Write to a file from PHP

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s