$file = 'myFile.php';
if (file_exists($file)) {
unlink($file);
}
The code above deletes myFile.php.
This time, I like to delete myDirectory instead of myFile.php.
How can I delete myDirectory ?
The would-be code below doesn’t work correctly, but I hope it shows what I want.
$directory = 'myDirectoy';
if (directory_exists($directory)) {
delete($directory);
}
Hi dotJoon,
The function you need is actually [fphp]rmdir[/fphp]. The PHP documentation has a full list of all the filesystem functions which you might find useful.
To remove an entire directory along with all sub directories recursively use the following code snippet.
rmdirr(‘path/to/dir’);
/**
Function to remove directory
* Depends on cleardir
*/
function rmdirr ($dir)
{
if (is_dir ($dir) && !is_link ($dir))
{
return cleardir ($dir) ? rmdir ($dir) : false;
}
return unlink ($dir);
}
/**
Function to clear a directory recursively
* Depends on rmdirr
*/
function cleardir ($dir)
{
if (!($dir = dir ($dir)))
{
return false;
}
while (false !== $item = $dir->read())
{
if ($item != '.' && $item != '..' && !rmdirr ($dir->path . DIRECTORY_SEPARATOR . $item))
{
$dir->close();
return false;
}
}
$dir->close();
return true;
}