The unlink Function

The unlink function deletes a file at the specified path. The function returns true upon successful deletion and false in case of an error. It accepts a string with the file path as a parameter.

Syntax

phpunlink(filename);

Example

Let's delete the file test.txt in the current directory:

php<?php
  $res = unlink('test.txt');
  var_dump($res);
?>

Code execution result:

phptrue

Example

Let's try to delete a non-existent file:

php<?php
  $res = unlink('nonexistent.txt');
  var_dump($res);
?>

Code execution result:

phpfalse

Example

Deleting a file with a check for its existence:

php<?php
  $file = 'data.txt';
  if (file_exists($file)) {
    $res = unlink($file);
    echo $res ? 'File deleted' : 'Delete error';
  } else {
    echo 'File not found';
  }
?>

See Also

  • the rmdir function,
    which deletes a directory
  • the file_exists function,
    which checks for the existence of a file
  • the is_writable function,
    which checks write permissions