You are on page 1of 8



Prepared by: Munirah Abd

PHP has some powerful file handling functions to manage files in a sever. Some of these functions requires some special settings at php.ini and some are available by default. We can open a file, write read and manage it by different functions.

PHP File open to read internal file

<? // This is at root of the file using this script $filename = "delete.htm";. // opening the file in read mode $fd = fopen ($filename, "r"); // reading the content of the file $contents = fread ($fd, filesize($filename)); // Closing the file pointer fclose ($fd); // printing the file content of the file echo $contents; ?>

PHP File Write function

Please note that we have to open the file in write mode and if write permission is there then only we can open it in write mode. If the file does not exist then one new file will be created.

<? // Store some text to enter inside the file $body_content="This is my content"; // file name $file_name="test_file.txt"; // Open the file in write mode, if file does not exist then it will be created. $fp = fopen ($file_name, "w"); // entering data to the file fwrite ($fp,$body_content); // closing the file pointer fclose ($fp); // changing the file permission. chmod($file_name,0777); ?>

PHP File delete using unlink function

We can delete files by giving its URL or path in PHP by using unlink command. This command will work only if write permission is given to the folder or file. Without this the delete command will fail.
unlink($path); $path="images/all11.css"; if(unlink($path)) echo "Deleted file ";

Deleting all files of a directory

develop a function and to this function we will post directory name as parameter and the function will use unlink command to remove files by looping through all the files of the directory. function EmptyDir($dir) { $handle=opendir($dir); while (($file = readdir($handle))!==false) { echo "$file <br>"; @unlink($dir.'/'.$file); } closedir($handle); } EmptyDir('images');

PHP directory listing

// open the current directory by opendir $handle=opendir("."); while (($file = readdir($handle))!==false) { echo "$file <br>";