Insane Visions - Basic PHP File Handling Tutorial :: Premium PHP Scripts - AdaptCMS, AdaptBB, OneCMS
Basic PHP File Handling at Mar 16, 08 - 9:54 pm

Views: 13,662 Type: PHP Experience Level: Medium
We've mostly focused on MySQL-type tutorials, but we'll show you in this tutorial the basics of file handling. This includes opening a directory and listing the files, opening a file and showing it's contents and opening, then modifying a file. Deleting a file too!
Reading a Directory
<?php
if ($handle = opendir("folder")) {
while (false !== ($file = readdir($handle))) {
if ($file != '.' and $file != '..') {
echo "<a href='.$file.'>".$file."</a><br />";
}
}
closedir($handle);
}
?>
Alright we have several things going on. First opendir simply opens a directory, replace folder with the name of the folder and if needed, the path too. The while loop then goes through file-by-file in the directory, the if statement excludes showing two non-files, you can exclude any files you wish too. After a simple echo displaying the filename, we then close the directory.
Showing a File
<?php
$file = '/path/to/file.php';
$handle = fopen($file, 'r');
$contents = fread($handle, filesize($file));
echo $contents;
fclose($handle);
?>
There are several ways to open and then display the contents of a file, but this example is for local files. You will see the fopen takes the file URL and then type r (meaning it will read the file, nothing else) onto the fread function. fread then gets the contents of the file, including a PHP file. fclose closes the connection after displaying the contents of the file.
Writing to a File
<?php
$contents = 'hey this is just a test, bla bla bla';
$handle = fopen('/path/to/file.php', 'w');
fwrite($handle, $contents);
fclose($handle);
?>
Okay first of all, if you do set the path to a non-existant file, it will attempt to create the file. If successfull it will replace the contents of the file with what you set in that "$contents" variable.
Setting the path and using fopen with type w, lets us open the file to write. fwrite then takes the "$contents" variable, putting the contents into the file and then closing it with fclose.
Deleting a File
<?php
unlink('/path/to/file.php');
?>
Not much explanation is needed, simply put in the path to the file you want to delete and wuvala.
Conclusion
We'll be doing more intermediate-expert tutorials mixed in with this basic tutorials in the future. Being able to open a directory, open and show a file, open and write a file as well as deleting a file are important PHP basics. Happy coding!
Download: 
Rating:    
| Guest, Jun 06, 08 - 7:32 am | | Exellent tutorial. Simple and straight forward. Could do with some comments though to explain why you need to do this step and such. But otherwise its great! Well done! |
|