PHP Delete File

Deleting a file is done using the PHP unlink command. At one time or another you will want to delete some file from your web server and you will need to use the unlink command to do it. The PHP delete file tutorial below will get you up to speed on deleting files in PHP.

At first, the name of the command may sound strange, but when you realise that storing files is simply placing data on a disk and then making a link to that data, the name unlink becomes more sensible. What unlink does is remove the link which pointed to a file, effectively deleting it.

To see how easy it is to delete a file in PHP, have a look at our PHP delete file tutorial below.

PHP unlink Syntax

The syntax for the unlink command is just as straightforward as the other file manipulation commands you have seen in our other PHP tutorials.

It is as follows:


Where $fileName is the name of the file to be deleted.

PHP unlink Example - Deleting a file in PHP

To delete a file in PHP, we simply pass the name of the file to be deleted to the unlink function. Here is an example of deleting a file using PHP:

$fileName = 'test.txt';

The code above will try to delete the file called test.txt in the current directory. By default, files not specified using an absolute path will be accessed relative to the current directory, that is, the directory which the PHP script containing the function resides in.

PHP unlink using an absolute path or a relative path

The above code would delete (from the current directory) the file called "test.txt". If we needed to delete files from directories other than the current directory, we would need to specify the full (or absolute) path to the file like:


We may also use a relative path when passing the filename to the unlink function:


Use the PHP delete file function, unlink, with care as you may accidentally delete important files with it. PHP does not use any Recycle Bin or Trashcan when deleting files! Any file that the web server has permission to write to may be deleted (perhaps irrecoverably) using the unlink command.

If you get an error when trying to use PHP to delete a file, then chances are that you do not have the appropriate permissions to modify that file. Ensure that the user which the web server runs as has write permissions on the file or folder which the file resides in.

We hope the PHP delete file tutorial above was helpful. You may also find our PHP write file tutorial helpful.

Link to this Page

Thank Tutorial Arena for This Tutorial.
Show your appreciation with a +1...