How to delete a file
Short answer
Check that the file exists and delete it with unlink():
<?php
$file = sys_get_temp_dir() . '/recipe-delete.txt';
file_put_contents($file, 'temp');
if (file_exists($file)) {
unlink($file);
}
var_dump(file_exists($file));Output:
bool(false)A folder with files
rmdir() removes only an empty folder, so the files are deleted first:
<?php
$dir = sys_get_temp_dir() . '/recipe-remove';
if (!is_dir($dir)) {
mkdir($dir);
}
file_put_contents($dir . '/a.txt', '');
file_put_contents($dir . '/b.txt', '');
foreach (glob($dir . '/*') as $file) {
unlink($file);
}
rmdir($dir);
var_dump(is_dir($dir));Output:
bool(false)Functions used in this recipe
- unlink — Deletes a file.
- file_exists — Checks whether a file or folder exists.
- rmdir — Removes an empty folder.