PHP Delete File

Summary: in this tutorial, you will learn how to delete a file in PHP using the unlink() function.

Introduction to the PHP delete file function #

To delete a file, you use the unlink() function:

unlink ( string $filename , resource $context = ? ) : boolCode language: PHP (php)

The unlink() function has two parameters:

  • $filename is the full path to the file that you want to delete.
  • $context is a valid context resource.

The unlink() function returns true if it deletes the file successfully or false otherwise. If the $filename doesn’t exist, the unlink() function also issues a warning and returns false.

PHP delete file examples #

Let’s take some examples of using the unlink() function.

1) Simple PHP delete file example #

The following example uses the unlink() function to delete the readme.txt file:

<?php

$filename = 'readme.txt';

if (unlink($filename)) {
	echo 'The file ' . $filename . ' was deleted successfully!';
} else {
	echo 'There was a error deleting the file ' . $filename;
}
Code language: HTML, XML (xml)

2) Delete all files in a directory that match a pattern #

The following example deletes all files with the .tmp extension:

<?php

$dir = 'temp/';
array_map('unlink', glob("{$dir}*.tmp"));Code language: HTML, XML (xml)

How it works.

  • First, define a variable that stores the path to the directory in which you want to delete files.
  • Second, use the glob() function to search for all files in the directory $dir that has the *.tmp extension and pass it result to the array_map() function to delete the files.

Generally, you can change the pattern to delete all matching files in a directory using the array_map(), unlink() and glob() functions.

Summary #

  • Use PHP unlink() function to delete a file.
Did you find this tutorial useful?