Delete File

Deleting files 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.

Unlink in PHP

$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:

$myFile = "testFile.txt";
$myFileLink = fopen($myFile, 'w') or die("can't open file");
$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.

If you enjoyed this resource, support me by sharing this page with others.
Share on Facebook
Share on StumbleUpon
Digg this
Tweet about this on Twitter
Share on Reddit

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.