File handling in php

The fopen() function is also used to create a file. fopen() checks first if file exist then it just open the file else it create the file first and then open. fwrite() used to write text in the file.
* Make sure that directory should have write permissions to create the file.

<?php $myfile = fopen("coding4developers.txt", "w") or die("Unable to open file!"); $txt = "Running\n"; fwrite($myfile, $txt); $txt = "Code\n"; fwrite($myfile, $txt); fclose($myfile); ?>

If you run this code again after changing text the old text will be erased and new text will be written.
And if don't want to erase the code you can use following code.

<?php $txt = "Coding 4 developers"; $myfile = file_put_contents('logs.txt', $txt.PHP_EOL , FILE_APPEND); ?>

You also can check weather file exist or not:

<?php if(!file_exists("logs.txt")) { die("File not found"); } else { $file=fopen("logs.txt","r"); } ?>

Share This: