Deleting files with PHP
Wednesday, August 6th, 2008 at 9:49am, in File Management, written by Tom Foyster
Following our tutorials on uploading files and listing files, this tutorial will walk you through deleting files from a directory. This is done using the unlink() function.
To start off, we create a function and pull through the file we're going to delete.
function file_delete($file) {
}
Then, we need to make sure that the file we're trying to delete isn't currently open. Confusing, we also have to make sure it's open before we do this!
function file_delete($file) {
$ofile = fopen($file, 'w') or die("error opening file");
fclose($ofile)
}
The last part of this function is to delete the file. Easy no?
function file_delete($file) {
$ofile = fopen($file, 'w') or die("error opening file");
fclose($ofile)
unlink($file)
}
Finally, we call the function from the page, passing through the file path for the file we want to delete.
file_delete("images/intro.jpg");

















Comments on this article
By Tom, Monday, August 11th, 2008 at 10:49am
Humm, I think 'sucks' is a little strong. We have simply gone around it in different ways. In my function, if the file cannot be opened, ie, doesn't exist, then it dies with an error. You simply check to see if the file exists or not using is_file. Two different solutions to the same problem.
Thanks for your comment, Onur.
By onur, Monday, August 11th, 2008 at 10:36am
sucks!
function deleteFile($filename)
{
if(!is_file($filename))
{
echo "Unable to open file {$filename}";
return false;
} else {
return unlink($filename);
}
}
?>
Please log in to post a comment about this article.