PHP: How to Delete a File CodeUnit 27 JUN 2009

PHPThe simplest way to delete a file in PHP is to make use of the unlink function.

‘Unlink function’ you ask?

Well the thought behind the name of the unlink function is that when you view the contents of a directory, the files that you see are only there because the operating system or application that you are using has a list of those files linked to that directory. So using this thinking, by unlinking a file you are essentially causing the system to forget about its existence, in other words, you have now deleted that file.

Tip: to make sure you can delete a file, you first need to be sure that no other program is currently using it. A good way of doing this is first to attempt to open the file and then use the fclose function to close it back down again.

So assuming a file named testFile.txt exists:

$myFile = “testFile.txt”;
$fh = fopen($myFile, ‘w’) or die(“can’t open file”);

The next step is of course to now delete the file. So:

$myFile = “testFile.txt”;

There you go, the testFile.txt file should now be removed from the system.

Naturally, at this step it is quite important to point out that the unlink function is particularly dangerous, simply because if you are not 100% sure of what you are deleting, you run the risk of bringing your whole system down by unlinking all the wrong files. In other words, play cautiously indeed!

Related Posts:

About Craig Lotter

South African software architect and developer at Touchwork. Husband to a cupcake baker and father to two little girls. I don't have time for myself any more.