Home » Tutorials » PHP » Delete File

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

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.



Link/cite this page

If you use any of the content on this page in your own work, please use the code below to cite this page as the source of the content.

  • Stewart, Suzy. "Delete File". After Hours Programming. Accessed on April 23, 2024. https://www.afterhoursprogramming.com/tutorial/php/delete-file/.

  • Stewart, Suzy. "Delete File". After Hours Programming, https://www.afterhoursprogramming.com/tutorial/php/delete-file/. Accessed 23 April, 2024.

  • Stewart, Suzy. Delete File. After Hours Programming. Retrieved from https://www.afterhoursprogramming.com/tutorial/php/delete-file/.



Leave a Comment

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