253 of 410 menu

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

unlink(filename);

Example

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

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

Code execution result:

true

Example

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

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

Code execution result:

false

Example

Deleting a file with a check for its existence:

<?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
byenru