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:


<?php
$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:


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

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

Advertisements

Read & Return Data From Files Into PHP


Reading File Data

If you have written data to a file from PHP, or you have a file on your server you need to read with PHP, there are quite a few ways you can do it. The four ways we will cover here are fread (), fgets (), file (), and file_get_contents(). The one you choose is based upon your needs, and how the data in the file you are accessing is formatted.

PHP File Upload Security Ideas


Some tips of file uploads With PHP Safer.
When you allow an users to upload files to your website, you are putting yourself at a security risk

  • Check the referrer: Check to make sure that the information being sent to your script is from your website and not an outside source. While this information can be faked, it’s still a good idea to check.
  • Restrict file types: You can check the mime-type and file extension and only allow certain types to be uploaded.
  • Rename files: You can rename the files that are uploaded. In doing so, check for double-barreld extensions like yourfile.php.gif and eliminate extensions you don’t allow, or remove the file completely.
  • Change permissions: Change the permissions on the upload folder so that files within it are not executable.