How to write to a flat file with PHP

Sometimes writing to a file is much easier that writing to a database. It is quite a tedious job to create a database, create a user to point to a database then create table and so on.

With a flat file you can just create a blank file (with any extension). I prefer still to use .php file so that people cannot read the file via web.

Here is the code to write and append to a file.

$name = "anyname"; $email = "anyemail";
$myFile = "yourdatafile.php";
$fh = fopen($myFile, 'a') or die("Failed to open file.");
$stringData = "$name;;$email\n";
fwrite($fh, $stringData);

Make sure you set your file to 666 (writable). If you want to overwrite each time data is saved, use fopen($myFile, ‘w’) ~ parameter ‘w’ instead of ‘a’

One thought on “How to write to a flat file with PHP

  1. Pingback: Technology . Business . Life » How to randomly read line from a file

Leave a Reply

Your email address will not be published. Required fields are marked *