You can use the Symfony Filesystem component, to avoid re-inventing the wheel, so you can do
use Symfony\Component\Filesystem\Filesystem;
$filesystem = new Filesystem();
if ($filesystem->exists('/home/dir')) {
$filesystem->remove('/home/dir');
}
If you prefer to manage the code yourself, here's the Symfony codebase for the relevant methods
class MyFilesystem
{
private function toIterator($files)
{
if (!$files instanceof \Traversable) {
$files = new \ArrayObject(is_array($files) ? $files : array($files));
}
return $files;
}
public function remove($files)
{
$files = iterator_to_array($this->toIterator($files));
$files = array_reverse($files);
foreach ($files as $file) {
if (!file_exists($file) && !is_link($file)) {
continue;
}
if (is_dir($file) && !is_link($file)) {
$this->remove(new \FilesystemIterator($file));
if (true !== @rmdir($file)) {
throw new \Exception(sprintf('Failed to remove directory "%s".', $file), 0, null, $file);
}
} else {
// https://bugs.php.net/bug.php?id=52176
if ('\\' === DIRECTORY_SEPARATOR && is_dir($file)) {
if (true !== @rmdir($file)) {
throw new \Exception(sprintf('Failed to remove file "%s".', $file), 0, null, $file);
}
} else {
if (true !== @unlink($file)) {
throw new \Exception(sprintf('Failed to remove file "%s".', $file), 0, null, $file);
}
}
}
}
}
public function exists($files)
{
foreach ($this->toIterator($files) as $file) {
if (!file_exists($file)) {
return false;
}
}
return true;
}
}