Friday, August 13, 2010

How To Delete Files Using PHP unlink Function

Deleting a file using PHP is done by using the unlink function.

Such a simple function with so much power! You need to use extreme caution when using the unlink function, as you don’t want to accidentally delete a crucial file that is needed elsewhere for other functions.


You can not delete a file that is already open using the fopen() function, as it is already being used. However, once you close a file you have the ability to delete it.

If the file is already opened, we need to use the fclose function to close the file. Remember how it’s done:
fclose($file);
This is assuming the file that is opened is assigned the variable $file previously. (See fopen())

Now that the file has been closed, you have the ability to delete the file:
$file = “myfile.txt”;
unlink($file);
First, you define which file you wish to delete. In this case, the file “myfile.txt” is defined using the variable “$file”.

Once you have defined the file, you then delete it using the unlink function.

After executing the unlink function, the file will then be removed.

No comments:

Post a Comment