Home » PHP Deleting Files: A Tutorial with Examples

PHP Deleting Files: A Tutorial with Examples

Deleting files in PHP is a common task in file management, whether for removing temporary files, cleaning up uploads, or managing user data.

In this tutorial, we will cover:

1. Deleting a Single File with unlink()

The unlink() function is used to delete a file in PHP.

Syntax:

unlink(string $filename): bool
  • $filename – The path to the file to be deleted.
  • Returns true on success and false on failure.

Example: Deleting a File

<?php
$file = "sample.txt";

if (unlink($file)) {
    echo "File deleted successfully!";
} else {
    echo "Failed to delete file!";
}
?>
  • This script deletes sample.txt if it exists.

2. Checking if a File Exists Before Deleting

Deleting a file that does not exist will cause an error. Use file_exists() before calling unlink().

Example:

<?php
$file = "backup.txt";

if (file_exists($file)) {
    if (unlink($file)) {
        echo "File deleted successfully!";
    } else {
        echo "Failed to delete file!";
    }
} else {
    echo "File does not exist!";
}
?>
  • Checks if backup.txt exists before attempting deletion.

3. Handling Errors While Deleting Files

If unlink() fails, we can use error_get_last() to retrieve error details.

Example: Handling Deletion Errors

<?php
$file = "protected_file.txt";

if (!unlink($file)) {
    $error = error_get_last();
    echo "File deletion failed! Error: " . $error['message'];
} else {
    echo "File deleted successfully!";
}
?>
  • Outputs error details if deletion fails.

4. Deleting Multiple Files

To delete multiple files, loop through an array of filenames.

Example: Deleting Multiple Files

<?php
$files = ["file1.txt", "file2.txt", "file3.txt"];

foreach ($files as $file) {
    if (file_exists($file)) {
        unlink($file);
        echo "Deleted $file <br>";
    } else {
        echo "$file does not exist! <br>";
    }
}
?>
  • Deletes multiple files in a single script.

5. Deleting Files with Specific Extensions

You can delete files of a certain type (e.g., .log files) using glob().

Example: Deleting .log Files

<?php
$logFiles = glob("*.log"); // Get all .log files

foreach ($logFiles as $file) {
    if (unlink($file)) {
        echo "Deleted $file <br>";
    } else {
        echo "Failed to delete $file <br>";
    }
}
?>
  • Deletes all .log files in the current directory.

6. Deleting Files Older Than a Certain Date

You can delete files older than a certain time period.

Example: Deleting Files Older Than 7 Days

<?php
$files = glob("uploads/*"); // Get all files in 'uploads/' directory
$now = time();

foreach ($files as $file) {
    if (is_file($file)) {
        if ($now - filemtime($file) > 7 * 24 * 60 * 60) { // 7 days in seconds
            unlink($file);
            echo "Deleted old file: $file <br>";
        }
    }
}
?>
  • Deletes files older than 7 days from the uploads/ folder.

7. Deleting an Empty Directory

Use rmdir() to delete an empty folder.

Example:

<?php
$dir = "empty_folder";

if (is_dir($dir) && rmdir($dir)) {
    echo "Directory deleted successfully!";
} else {
    echo "Failed to delete directory!";
}
?>
  • The folder must be empty before deletion.

8. Deleting All Files in a Folder

To delete all files in a folder but keep the folder, use a loop.

Example:

<?php
$folder = "cache/";
$files = glob($folder . "*"); // Get all files

foreach ($files as $file) {
    if (is_file($file)) {
        unlink($file);
        echo "Deleted: $file <br>";
    }
}
?>
  • Deletes all files in the cache/ folder but keeps the folder itself.

9. Deleting a Folder and Its Contents

To delete a folder and all its files, use recursion.

Example:

<?php
function deleteFolder($folder) {
    if (!is_dir($folder)) return false;
    
    foreach (scandir($folder) as $item) {
        if ($item == '.' || $item == '..') continue;
        $path = $folder . "/" . $item;
        is_dir($path) ? deleteFolder($path) : unlink($path);
    }

    return rmdir($folder);
}

$folder = "old_logs";
if (deleteFolder($folder)) {
    echo "Folder deleted successfully!";
} else {
    echo "Failed to delete folder!";
}
?>
  • Deletes all files and subdirectories before removing the folder.

10. Deleting Files via User Input (Secure Deletion)

Allowing users to delete files can be risky. Always sanitize inputs and restrict deletions to certain folders.

Example: Secure File Deletion

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["file"])) {
    $folder = "uploads/";
    $file = basename($_POST["file"]); // Sanitize filename
    $fullPath = $folder . $file;

    if (file_exists($fullPath) && strpos(realpath($fullPath), realpath($folder)) === 0) {
        unlink($fullPath);
        echo "File deleted successfully!";
    } else {
        echo "Invalid file!";
    }
}
?>

<form method="post">
    <input type="text" name="file" placeholder="Enter filename">
    <input type="submit" value="Delete File">
</form>
  • Sanitizes user input and restricts deletions to the uploads/ folder.

Conclusion

  • Use unlink() to delete files.
  • Always check if the file exists before deleting.
  • Handle errors using error_get_last().
  • Delete multiple files using loops.
  • Remove old files by checking timestamps.
  • Use rmdir() to delete empty directories.
  • Use recursive functions to delete a folder and its contents.
  • Always sanitize user input when allowing file deletions.

You may also like