To keep your server organized and free up space, you often need to delete temporary files or decommission old data. PHP uses the unlink() function to remove files from the system.
unlink() FunctionThe unlink() function is used to delete a file permanently. It returns TRUE on success and FALSE on failure.
<?php
unlink("testfile.txt");
?>
Trying to delete a file that doesn't exist will trigger a PHP warning. It is best practice to use file_exists() before attempting to delete.
<?php
$file = "testfile.txt";
if (file_exists($file)) {
if (unlink($file)) {
echo "File deleted successfully.";
} else {
echo "Error deleting the file.";
}
} else {
echo "File does not exist.";
}
?>
unlink(), it cannot be recovered from a "recycle bin." It is gone from the server permanently.
unlink() with a path directly from user input (like unlink($_GET['file'])). A hacker could use "Path Traversal" (e.g., ../../index.php) to delete your entire website.
rmdir(). However, the directory must be empty first.
unlink() is the primary function for file deletion.unlink() in a file_exists() check.unlink() returns false.