How to delete a file if exists in PHP?
First, define a vari
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.<?php
$dir = 'temp/';
array_map('unlink', glob("{$dir}*.tmp"));
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;
}