Skip to content

How to delete a file using PHP?

Last updated on January 28, 2021

You can delete files from the server with PHP’s file system function unlink() which will delete/remove the files.

Using unlink you can removes all types of files like images, documents, media files .. etc. It returns TRUE on success or FALSE on failure.

If there is a problem, it is most likely because you do not have permission to delete the file. The directory must be readable by the user in order to remove the file.

You can use is_readable() the function, which tells whether a file exists or not and is readable or not. It is best practice to check file existence and permissions before attempting to delete action in order to avoid unexpected errors.

Below is an example, it shows how to use both functions – unlink() and is_redable().

<?php
$file = "/test/my_test_file.txt";
 
if (is_readable($file) && unlink($file)) {
    echo "The file has been deleted";
} else {
    echo "The file was not found or not readable and could not be deleted";
} 
?>

if you run the above script two times, the first time you will get the output as The file has been deleted, if the file exists. and for the next run, you will get The file was not found or not readable and could not be deleted

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments