PHP Function Reference

PHP unlink() Function



The PHP unlink() function deletes the specified file.

Syntax

unlink(filename, context)

Parameters

filename Required. Specify the path to the file to delete.
context Optional. Specify the context of the file handle. Context is a set of options that can modify the behavior of a stream.

Return Value

Returns true on success or false on failure.

Exceptions

Upon failure, an E_WARNING level error is thrown.

Example:

Lets assume that we have a file called test.txt in the current working directory. The example below demonstrates on using this function to delete this file.

<?php
$file = 'test.txt';

//deleting the $file if exists
if (file_exists($file)) {
  echo "$file contains: ".filesize($file)." bytes\n";
  if(unlink($file)) {
    echo "$file is successfully deleted.";
  } else {
    echo "$file can not be deleted.";
  }
} else {
  echo "$file is not found.";
}
?>

The output of the above code will be:

test.txt contains: 48 bytes
test.txt is successfully deleted.

❮ PHP Filesystem Reference