Skip to content

Deleting a file in PHP

In PHP, deleting a file is done using the unlink() function. This function allows you to remove a specified file from the filesystem.

Syntax of the unlink() Function

php

Copy code

unlink(filename)

  • filename: The path to the file you want to delete.

The unlink() function returns TRUE on successful deletion and FALSE on failure.

Basic Example of Deleting a File

Let’s say you have a file named “example.txt” that you want to delete:

php

Copy code

<?php

$file = “example.txt”;

if (unlink($file)) {

    echo “File deleted successfully.”;

} else {

    echo “Failed to delete the file.”;

}

?>

In this example:

  • The unlink() function attempts to delete “example.txt”.
  • If successful, it outputs “File deleted successfully”; otherwise, it outputs an error message.

Checking if a File Exists Before Deleting

To avoid errors, it’s a good idea to check if the file exists using file_exists() before calling unlink().

php

Copy code

<?php

$file = “example.txt”;

if (file_exists($file)) {

    if (unlink($file)) {

        echo “File deleted successfully.”;

    } else {

        echo “Failed to delete the file.”;

    }

} else {

    echo “The file does not exist.”;

}

?>

In this example:

  • file_exists($file) checks if “example.txt” is present.
  • If the file exists, unlink($file) is called to delete it.