How to Delete a File in PHP if it Exists

Summary:

Use the file_exists function before using the unlink function if you want to delete a file if it exists in PHP. This isn't necessary as the unlink function silently fails. Check out the article for more details.

Quick Example: Delete a File in PHP if it Exists

This article explains how to delete a file in PHP if it exists. It features the PHP unlink function for deleting an existing file in PHP.

<?php
    $filename = 'virtual.txt';
 
    if(file_exists($filename))
    {
        $status  = unlink($filename) ? 'The file '.$filename.' has been deleted' : 'Error deleting '.$filename;
        echo $status;
    }
 
    else
    {
        echo 'The file '.$filename.' doesnot exist';
    }
 
 
//Output
//The file virtual.txt doesnot exist
 
?>

If you’re not familiar with file operations in PHP, check out how to read and write files in PHP. This article focuses on delete file PHP. Let’s jump straight to the subject. 

Delete a File in PHP – A Graphical Overview

The program for deleting a file in PHP is quite straightforward. PHP function unlink helps is removing a file. It expects a string argument as the file path. The function returns true on success and false if something goes unintended. In the case of a non-existing file, it issues a warning.

Here’s an illustration of the program’s logical flow.

delete a file in PHP

1 – Delete File in PHP Using unlink and ignore the unfound file warning.

PHP unlink function deletes a file. If the file doesn’t exist, it raises a warning. Here’s the function signature

unlink(string $filename, ?resource $context = null): bool

The filename is the path to the file. The following example demonstrates how to delete an existing file in PHP using the unlink function.

<?php
$filename = 'intro.txt';
 
if(unlink($filename))
{
    echo 'The file '.$filename.' has been deleted';
}
 
else
{
    echo 'The file '.$filename.' doesnot exist';
}
 
//Output
//The file intro.txt has been deleted
?>

The example checks if the unlink function successfully deletes a file, else it outputs an error message. 

Here the file ‘intro.txt’ exists in the same folder with this example PHP file. However, sometimes the path names may not resolve as intended. In that cases, absolute paths can be handy. Luckily, we have a function for that in PHP. Let’s see that function in the following example.

<?php
$filename = 'intro.txt';
 
$absolutePath = realpath($filename); //C:\PHP\intro.txt
 
if(unlink($absolutePath))
{
    echo 'The file '.$filename.' has been deleted';
}
 
else
{
    echo 'The file '.$filename.' doesnot exist';
}
 
//Output
//The file intro.txt has been deleted
?>

PHP realpath comes in handy when trying to use absolute paths. It takes a relative path and returns the absolute path to that file.

2 – Delete Multiple Files in PHP Using Patterns and echoing the Warning

PHP glob function returns an array of file paths that matches a pattern. The pattern is a regex string. This function, together with the unlink, can help delete multiple files. The following example deletes all the files with the .txt extension.

<?php
 
array_map(function($filename) {
    if(unlink($filename))
    {
        echo 'The file '.$filename.' has been deleted';
    }
 
    else
    {
        echo 'The file '.$filename.' doesnot exist';
    }
}, glob('*.txt'));
 
//Output
//The file intro.txt has been deleted
//The file main.txt has been deleted
//The file exit.txt has been deleted
 
?>

Voila! It removes all the .txt files in the same directory. The array map iterates over the file paths returned by the glob function and unlink them one by one.

3 – PHP Delete File with Error Handling

As seen already, the unlink function issues a runtime warning. All we need is to handle the error gracefully. One way is to check if a file exists beforehand – up next. Another approach could be using error handling to at least define a custom function for a scenario of a non-existent file.

We’ll be using PHP set_error_handler function. This function lets you define a custom call back function for handling warnings and errors in PHP. We won’t dive deep into the details of the function itself but the following example will make sense hopefully.

<?php
set_error_handler(function($errl, $errm) 
{
    echo $errm.PHP_EOL;  
});

$filename = 'mystery.txt';
 
if(unlink($filename))
{
    echo 'The file '.$filename.' has been deleted';
}
 
else
{
    echo 'Error deleting '.$filename.PHP_EOL;
}
 
//Output
//unlink(mystery.txt): No such file or directory
//Error deleting mystery.txt
?>

As simple as possible, we defined a callback as the set_error_handler argument and all it does is log the error message to the console. We have kept it simple for the purpose of demo but the callback function could do much more than this. For instance, logging the error message to a log file.

4 – Check & Delete File PHP if it Exists 

PHP unlink function issues a warning if a file doesn’t exist. We can adopt a more proactive approach to avoid this scenario. We can check if the file exists only then call the unlink function, thus catering for this edge case. The following example does that.

<?php
    $filename = 'virtual.txt';
 
    if(file_exists($filename))
    {
        $status  = unlink($filename) ? 'The file '.$filename.' has been deleted' : 'Error deleting '.$filename;
        echo $status;
    }
 
    else
    {
        echo 'The file '.$filename.' doesnot exist';
    }
 
 
//Output
//The file virtual.txt doesnot exist
 
?>

Cool! The example uses PHP file_exists function to check if the file exists. If yes, only then does it call the unlink function. 

Create a Log File in PHP

Before we wrap up the article, let’s go the extra mile and learn how to create a log file that would keep a history of all the delete operations, successful or unsuccessful. Logging information is a key feature of an application. It helps keep a record that could reveal any vulnerabilities and inconsistencies that may have occurred over time.

There are libraries out there for logging functions in almost every modern programming language. However, we will use PHP file_put_contents as we’re dealing with a relatively simple scenario.

<?php
 
  array_map(function($filename) {
      if(file_exists($filename))
      {
        $status  = unlink($filename) ? 'The file '.$filename.' has been deleted'.PHP_EOL : 'Error deleting '.$filename.PHP_EOL;
        file_put_contents('logs.txt', $status, FILE_APPEND);
      }
   
      else
      {
          $status = 'The file '.$filename.' doesnot exist'.PHP_EOL;
          file_put_contents('logs.txt', $status, FILE_APPEND);
      }
  }, ['intro.txt', 'main.txt', 'sub.txt','end.txt']);
   
?>

The file_put_contents is an amazing function that takes care of creating a file or appending to a file if it already exists. Here’s the content of the log file.

The file intro.txt has been deleted
The file main.txt has been deleted
The file sub.txt doesnot exist
The file end.txt doesnot exist

Voila! We’re all set now with logging.

Wrap Up

This article focuses on deleting file PHP function unlink. It features examples of deleting one or more files with the unlink function. Lastly, it also overviews an approach of checking if the file exists and, if so, then actually deleting it.

That’s all about it. We hope you’ve liked it. Stay tuned for more at FuelingPHP.

Want to learn more about PHP?

We have many fun articles related to PHP. You can explore these to learn more about PHP.

  Was this information helpful?

Can Your Career Use a Boost?

Check out our free PHP developer career guide. We created this guide as a resource to help fellow programmers level up their careers. This is an excellent resource whether you are new to programming or have been a professional for more than 15 years.

Click here to read the guide


Article Categories

Article Tags

© 2022 Confident.Systems