The unlink() function in PHP deletes a file from the filesystem. It returns true on success and false on failure.
Syntax:
unlink(string $filename, ?resource $context = null): boolParameters:
- $filename: Specifies the path of the file to delete.
- $context: An optional stream context used to modify the behavior of the stream.
Return Value:
- Returns true if the file is deleted successfully.
- Returns false if the deletion fails.
Deletes a File Using unlink()
The following example checks whether a file exists before deleting it.
<?php
$file = "example.txt";
if (is_file($file)) {
if (unlink($file)) {
echo "The file '$file' has been deleted.";
} else {
echo "Failed to delete the file.";
}
} else {
echo "The file does not exist.";
}
?>
- is_file() checks whether the specified path refers to a regular file.
- unlink() attempts to delete the file.
- The result determines whether a success or failure message is displayed.
Output:

Deletes an Uploaded File Using unlink()
The unlink() function can remove an uploaded file after it has been processed, provided the application is authorized to delete it.
<?php
$uploadedFile = "gfg.jpg";
if (is_file($uploadedFile)) {
if (unlink($uploadedFile)) {
echo "The uploaded file has been deleted.";
} else {
echo "Failed to delete the uploaded file.";
}
} else {
echo "The uploaded file does not exist.";
}
?>
- $uploadedFile specifies the path of the uploaded file.
- is_file() checks whether the file exists at the specified path.
- unlink() attempts to remove the file.
- The code displays a message based on the operation's result.
Note: In a real application, do not allow users to supply arbitrary file paths. Resolve the file from a trusted identifier and verify that the user is authorized to delete it.
Output:

Removes Empty Directories Using rmdir()
The unlink() function does not delete directories. PHP provides the rmdir() function to remove an empty directory.
<?php
$directory = "php-codes/uploads";
if (is_dir($directory)) {
if (rmdir($directory)) {
echo "Directory deleted successfully.";
} else {
echo "Failed to delete the directory.";
}
} else {
echo "Directory does not exist.";
}
?>
Note: rmdir() removes only empty directories. Files and subdirectories must be handled separately.
Output:

Best Practices
- Verify the file path before attempting deletion.
- Check the return value of unlink() to handle failures.
- Ensure the PHP process has the necessary filesystem permissions.
- Restrict deletion operations to authorized users and approved directories.
- Never pass unvalidated user input directly to unlink().
- Avoid deleting files based solely on a user-provided filename; use trusted file identifiers and verify ownership or access rights.