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? ๐Ÿš€