PHP File Deletion

PHP File Deletion – Delete Files Securely 🗑️

Sometimes, you just need to get rid of a file. Maybe it’s an old report, an expired user upload, or just a file that has overstayed its welcome. PHP makes file deletion easy with unlink()!


🔹 Deleting a File in PHP

The unlink() function removes a file from the server.

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

if (file_exists($file)) {
    unlink($file); // Delete the file
    echo "File deleted successfully! 🗑️";
} else {
    echo "File does not exist! ❌";
}
?>

Try It Now

Here’s what happens:

  • If the file exists, unlink() deletes it.
  • If the file is missing, we display an error message.

🔹 Deleting Files Uploaded by Users

Let’s say users upload files to an uploads/ folder. We can delete a specific uploaded file using PHP.

<?php
$uploadedFile = "uploads/user_avatar.png";

if (file_exists($uploadedFile)) {
    unlink($uploadedFile);
    echo "User avatar deleted! 🎯";
} else {
    echo "File not found! 🔍";
}
?>

Try It Now


🔹 Deleting Multiple Files

Need to delete multiple files? Loop through an array of filenames!

<?php
$files = ["report1.pdf", "report2.pdf", "report3.pdf"];

foreach ($files as $file) {
    if (file_exists($file)) {
        unlink($file);
        echo "$file deleted! 🗑️ <br>";
    } else {
        echo "$file not found! ❌ <br>";
    }
}
?>

Try It Now


🔹 Security Tips for File Deletion

Be careful when deleting files! Follow these security tips:

  • ✅ Ensure only valid files are deleted.
  • ✅ Prevent deletion of system files or essential scripts.
  • ✅ Restrict file deletions to a specific directory.

📝 Secure File Deletion Example

<?php
$directory = "uploads/";
$fileToDelete = "user_file.txt";

// Only allow deletions from the uploads folder
$fullPath = realpath($directory . $fileToDelete);

if (strpos($fullPath, realpath($directory)) === 0 && file_exists($fullPath)) {
    unlink($fullPath);
    echo "File deleted securely! 🔐";
} else {
    echo "Invalid file path! ❌";
}
?>

Try It Now


🎯 Key Takeaways

  • unlink() is used to delete files.
  • Always check if a file exists before deleting it.
  • Be cautious to prevent unintended file deletions.

📝 Practice Time!

Try deleting different files and observe the results. Can you add a condition to prevent deleting certain important files? 🚀