Danny 🎠 6 days ago
I LOVE THE NEW DESIGN SO MUCH AAAAAAAAAAH
nick 🤞 6 days ago
the new designs are finally here! still a few rough edges here and there, but we'll smooth them out. if you spot any bugs, tell us <3

Deleting files using PHP

Written by nick • 26.05.2025

PHP lets you delete files using the built-in unlink() function. It's easy to use, but you should always add basic checks to avoid deleting the wrong file or causing errors.


1. Basic file deletion

This is the most basic way to delete a file in PHP:

<?php
unlink('example.txt');

This deletes the file named example.txt from the same directory as your script. If the file doesn't exist, PHP will show a warning.


2. Add safety checks

To avoid errors or deleting the wrong thing, always check if the file exists before trying to remove it:

<?php
$filename = 'example.txt';

// Check if the file exists before deleting
if (file_exists($filename)) {
    // Delete the file
    unlink($filename);
    echo 'File deleted.';
} else {
    echo 'File does not exist.';
}

3. Best Practices

- Always double-check the file name and path before deleting.
- Prevent directory traversal: attackers might try ../../important.txt to escape the allowed folder and delete sensitive files.
- Use realpath() to get the actual file location and make sure it stays within an allowed directory (like uploads/).
- Make sure it's a real file, not a folder or special path, by using is_file().


4. Full example following best practices

Note: You only need this level of safety (like checking realpath()) if you're deleting files or folders based on user input — for example, from a URL like delete.php?file=example.txt. This protects against path traversal and accidental access to sensitive areas.

If you're only deleting files or folders that your own code controls and the paths are always safe, you can use the simpler version shown above. 👀

<?php
$filename = 'example.txt';

// Resolve base path to avoid path traversal
$realBase = realpath(__DIR__);
$realPath = realpath($filename);

// Ensure file is within allowed path
if ($realPath && strpos($realPath, $realBase) === 0) {
    if (is_file($realPath)) {
        if (unlink($realPath)) {
            echo 'File successfully deleted.';
        } else {
            echo 'Failed to delete file.';
        }
    } else {
        echo 'Not a valid file.';
    }
} else {
    echo 'Invalid file path.';
}