Expand To Show Full Article
How to Delete a File in PHP if it Exists with Code Examples in 2023
Skip to content
Home » How to Delete a File in PHP if it Exists with Code Examples in 2023

How to Delete a File in PHP if it Exists with Code Examples in 2023

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.

Delete a File in PHP if it Exists Code Example

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.

PHP Fundamentals Recommendations

This article is part of our content on PHP Fundamentals. It includes the core concepts that build upon the foundation of writing high-quality PHP code. If you are looking to grow your PHP development abilities. Check out the following recommended affiliate resources.

We do make a commission if you do choose to buy through our links. It is one of the ways that help support our mission here at FuelingPHP.

Book: Fundamentals of Web Development

This book is for you if you are starting to learn how to build websites. It is more than just an “intro to programming” book. You will learn the concepts and tips on what goes into creating a high-quality website. Today’s websites are more than text on a screen. They are highly complex applications that encourage user experience. Learn the fundamentals of good web development with this book.

Check it out on Amazon

Book: Programming in PHP (O’Reilly)

O’Reilly should not need any introduction. They are the top publishers when it comes to books on programming and technology. This book fits well within their vast library. If you are newer to the PHP language or want to keep a solid reference by your side. I highly recommend this book for your collection.

Check it out on Amazon

Book: Design Patterns in PHP

I highly recommend this book to any intermediate-level web developer. It takes the theories and best practices of writing high-quality code via design patterns and applies them to PHP. It is a great resource to take your career to the next level

Check it out on Amazon

Video Course: PHP Fundamentals (Pluralsight)

Want to quickly learn PHP? This PHP Fundamentals course is ideal for beginner PHP developers. It is a deep dive into the concepts, structures and well “fundamentals” of PHP development. It includes high-quality video & interactive resources that teach you really fast. I highly recommend this if you are getting started in your PHP journey.

Click here for a 10-day free trial to Pluralsight

Complete Learning Path: Web Development (Pluralsight)

You should definitely check out this learning path from Pluralsight. They have a huge list of video courses, training, and interactive lessons on growing your web development career. You get access to the full library of hundreds of resources for a single monthly subscription. It truly is like Netflix for your career.

Click here to see details (10-day free trial included)

Want more reviews? Check out our HUGE list of Beginner Web Development Books We’ve Researched and Reviewed for you.

Deleting Files in PHP

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.