PHP Delete File

PHP Delete file in php isn’t extremely common, but it is sometimes necessary. Always remember that you should hesitate before deleting anything. PHP doesn’t have a special undo for what you delete. Now that I have warned you, let’s burn some files to the ground.

PHP Delete File


Unlink in PHP

Example

$myFile = "testFolder/sampleDeleteFile.txt";
unlink($myFile) or die("Couldn't delete file");

As you can see, it doesn’t take too much to delete a file. If you run into problems deleting files, try opening and closing the file before you actually delete it. Like so:

Example

$myFile = "testFile.txt";
$myFileLink = fopen($myFile, 'w') or die("can't open file");
fclose($myFileLink);
$myFile = "testFolder/sampleDeleteFile.txt";
unlink($myFile) or die("Couldn't delete file");

I should note that this is more of a hack rather than good practice. Try to always close your files shortly after you open them. All you are doing with the code above is opening the file again to ensure that you actually close it.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.