File handling is an important part of any web application. You often need to open and process a file for different tasks. PHP has several functions for creating, reading, uploading, and editing files.
index.php ( fopen() & fread() ) <?php readfile("demo.txt"); ?> <?php $myfile = fopen("demo.txt", "r") or die("Unable to open file!"); echo fread($myfile,filesize("demo.txt")); fclose($myfile); ?>
demo.txt this is my demo file for testing file handling
index.php ( fopen() & fwrite() write(w) ) <?php $myfile = fopen("demo.txt", "w") or die("Unable to open file!"); $txt = "John Doen"; fwrite($myfile, $txt); $txt = "Jane Doen"; fwrite($myfile, $txt); fclose($myfile); ?>
index.php ( fopen() & fwrite() append (a) ) <?php $myfile = fopen("demo.txt", "a") or die("Unable to open file!"); $txt = "Donald Duckn"; fwrite($myfile, $txt); $txt = "Goofy Goofn"; fwrite($myfile, $txt); fclose($myfile); ?>