This article demonstrates how to delete a file in PHP.

In PHP, you can use the unlink() function to delete a file from the file system. It works similarly to the Unix C unlink() function.

Download Code

 
If the specified file is a symlink, the unlink() function deletes it. If the file does not exist, a PHP warning will be thrown. You might want to check if the file exists or not before calling the unlink() function. This can be done using the file_exists() function.

Download Code

 
Furthermore, if the file is a directory, the unlink() function will throw a PHP warning. It is advisable to check first whether the specified file is a directory or not. This can be done using the is_dir() function, which returns a boolean value depending on the result.

Download Code

 
If you want to delete multiple files, you can do so within a loop. To illustrate, the following solution iterates over an array of filenamesand deletes each file individually using unlink().

Download Code

That’s all there is to deleting a file in PHP.