Skip to content
PHP Logo

How can the "unlink" function in PHP be used to delete files from a specific directory?

To delete files from a specific directory using the "unlink" function in PHP, you need to provide the full path to the file you want to delete. This function will permanently remove the file from the directory. Make sure to handle errors and check if the file exists before attempting to delete it.

php
$directory = '/path/to/directory/';
$file_to_delete = $directory . 'file.txt';

if (file_exists($file_to_delete)) {
    if (unlink($file_to_delete)) {
        echo 'File deleted successfully.';
    } else {
        echo 'Unable to delete file.';
    }
} else {
    echo 'File does not exist.';
}