[PHP] Delete a file with PHP

Dieser Beitrag ist auch verfügbar in: German

Hi together,

today I wand to answer the question how to delete a file with PHP.

First of all we have to separate. Files on the web server or files on the local hard disk. First yes, second no.
PHP doesn’t have access to files of the local file system of a visitor. No server side programming language can do it. Also client side languages (like Javascript) can’t do it. Else it would be easy for every single webpage to delete randomly files from your computer. That would be an disaster.

But on the web server is it – partly – possible to delete files. Partly means that you can’t delete every file. Also this would be a disaster.

The PHP-Script needs the right to delete files or at least specific files. Under Linux is the right system very strict.

But in the normal situation is it not so complicated like it sounds like. Because usually you delete a file which you created with the script. Like a temporary file or a file from a user upload (a picture for example). Such a file was created by the PHP script and inherit it’s user rights. And also the script has the right to delete this file again.

But how?
Very simple. All we need is the PHP command for deleting a file and the path of the file itself. It fits all in one code line.

$res = unlink("testdatei.hm");

That’s it. In $res we get a return value. 1 = successful deleted or 0 = Couldn’t delete the file.

You can use relative as well as absolute paths.

That’s it. Hope it was helpful :)

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

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

I accept the Privacy Policy