Skip to content

Instantly share code, notes, and snippets.

@s-hiroshi
Created November 6, 2012 06:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save s-hiroshi/4022896 to your computer and use it in GitHub Desktop.
Save s-hiroshi/4022896 to your computer and use it in GitHub Desktop.
PHP > snippets > ディレクトリ削除
d/*
* ディレクトリ削除
*
* 中身のファイルを削除してからディレクトリを削除する。
*
* @param $dir 削除するディレクトリ。末尾/はなし
* @return bool ディレクトリ削除に成功したらtrue, 失敗はfalse
*/
function removeDirectory($dir)
{
// $dirが/で終わっている場合は/削除
if (strripos($dir, '/') === mb_strlen($dir, 'UTF-8')) {
$dir = rtrim($dir, '/');
}
// ディレクトリ内のファイルの削除
foreach(glob($dir . '/*.*') as $file) {
// ファイルの存在確認
if (file_exists($file) === false) {
return false;
}
// パーミッションエラー
if (file_exists($file)
&& !is_writable($file)
|| !is_writable(dirname($dir))
) {
return false;
}
// ファイル削除
if(unlink($file) === false) {
// 原因が特定できないエラー
return false;
}
}
// ディレクトリの存在確認
if (file_exists($dir) === false) {
return false;
}
// ディレクトリパーミッションエラー
if (file_exists($dir)
&& !is_writable($dir)
) {
return false;
}
// ディレクトリ削除
if (rmdir($dir) === false) {
// 原因が特定できないエラー
return false;
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment