HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

PHP File Delete

To keep your server organized and free up space, you often need to delete temporary files or decommission old data. PHP uses the unlink() function to remove files from the system.


1. The unlink() Function

The unlink() function is used to delete a file permanently. It returns TRUE on success and FALSE on failure.

<?php
    unlink("testfile.txt");
?>

2. Safety First: Checking Existence

Trying to delete a file that doesn't exist will trigger a PHP warning. It is best practice to use file_exists() before attempting to delete.

<?php
    $file = "testfile.txt";
    if (file_exists($file)) {
        if (unlink($file)) {
            echo "File deleted successfully.";
        } else {
            echo "Error deleting the file.";
        }
    } else {
        echo "File does not exist.";
    }
?>
Irreversible Action: Once a file is deleted using unlink(), it cannot be recovered from a "recycle bin." It is gone from the server permanently.
Security Risk: Never use unlink() with a path directly from user input (like unlink($_GET['file'])). A hacker could use "Path Traversal" (e.g., ../../index.php) to delete your entire website.
Pro Tip: If you need to delete an entire directory, use rmdir(). However, the directory must be empty first.

Key Takeaways

  • unlink() is the primary function for file deletion.
  • Always wrap unlink() in a file_exists() check.
  • Deletions are permanent and cannot be undone.
  • Strictly validate any file paths provided by users to prevent malicious deletions.
  • Check directory permissions if unlink() returns false.