我们有时候需要删除刚生成的临时文件,比如上传图片或者生成图片的时候,我们需要现在本地存储起来,然后再上传到图片服务器。当图片上传到服务器之后,那本地存储的图片就没用了,为了避免项目文件过大,所以删除本地的图片文件的就变得很有必要。
直接分享一段代码:
//需要传两个参数,一个是我们需要删除的文件路径,比如:
$path2= "./upload/picture/";
$this->delDirAndFile($path,true);
//这是删除的方法
public function delDirAndFile($path, $delDir = true) {
if (is_array($path)) {
foreach ($path as $subPath)
$this->delDirAndFile($subPath, $delDir);
}
if (is_dir($path)) {
$handle = opendir($path);
if ($handle) {
while (false !== ( $item = readdir($handle) )) {
if ($item != "." && $item != "..")
is_dir("$path/$item") ? $this->delDirAndFile("$path/$item", $delDir) : unlink("$path/$item");
}
closedir($handle);
if ($delDir)
return rmdir($path);
}
} else {
if (file_exists($path)) {
return unlink($path);
} else {
return FALSE;
}
}
clearstatcache();
}
以上就删除文件夹或者文件的代码部分。(顺便吐槽一句,编辑器的代码颜色看起来真难看。。。)
end