例如,我有一个名为“Temp”的文件夹,我想使用PHP删除或刷新该文件夹中的所有文件。我可以这样做吗?
当前回答
以下代码来自http://php.net/unlink:
/**
* Delete a file or recursively delete a directory
*
* @param string $str Path to file or directory
*/
function recursiveDelete($str) {
if (is_file($str)) {
return @unlink($str);
}
elseif (is_dir($str)) {
$scan = glob(rtrim($str,'/').'/*');
foreach($scan as $index=>$path) {
recursiveDelete($path);
}
return @rmdir($str);
}
}
其他回答
发布了一个通用的文件和文件夹处理类,用于复制,移动,删除,计算大小等,可以处理单个文件或一组文件夹。
https://gist.github.com/4689551
使用方法:
复制(或移动)一个文件或一组文件夹/文件:
$files = new Files();
$results = $files->copyOrMove('source/folder/optional-file', 'target/path', 'target-file-name-for-single-file.only', 'copy');
删除单个文件或删除路径下的所有文件和文件夹:
$files = new Files();
$results = $files->delete('source/folder/optional-file.name');
计算单个文件或一组文件夹中文件的大小:
$files = new Files();
$results = $files->calculateSize('source/folder/optional-file.name');
下面是一种使用标准PHP库(SPL)的更现代的方法。
$dir = "path/to/directory";
if(file_exists($dir)){
$di = new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS);
$ri = new RecursiveIteratorIterator($di, RecursiveIteratorIterator::CHILD_FIRST);
foreach ( $ri as $file ) {
$file->isDir() ? rmdir($file) : unlink($file);
}
}
对我来说,使用readdir的解决方案是最好的,而且非常有效。对于glob,该函数在某些情况下会失败。
// Remove a directory recursively
function removeDirectory($dirPath) {
if (! is_dir($dirPath)) {
return false;
}
if (substr($dirPath, strlen($dirPath) - 1, 1) != '/') {
$dirPath .= '/';
}
if ($handle = opendir($dirPath)) {
while (false !== ($sub = readdir($handle))) {
if ($sub != "." && $sub != ".." && $sub != "Thumb.db") {
$file = $dirPath . $sub;
if (is_dir($file)) {
removeDirectory($file);
} else {
unlink($file);
}
}
}
closedir($handle);
}
rmdir($dirPath);
}
$files = glob('path/to/temp/*'); // get all file names
foreach($files as $file){ // iterate files
if(is_file($file)) {
unlink($file); // delete file
}
}
如果你想删除像.htaccess这样的“隐藏”文件,你必须使用
$files = glob('path/to/temp/{,.}*', GLOB_BRACE);
foreach (new DirectoryIterator('/path/to/directory') as $fileInfo) {
if(!$fileInfo->isDot()) {
unlink($fileInfo->getPathname());
}
}
推荐文章
- 如何将XML转换成PHP数组?
- 如何将对象转换为数组?
- 从IP地址获取位置
- 获取数组值的键名
- HTTPS和SSL3_GET_SERVER_CERTIFICATE:证书验证失败,CA is OK
- PHP -获取bool值,当为false时返回false
- 如何删除文件中的特定行?
- 在foreach中通过引用传递
- 如何触发命令行PHP脚本的XDebug分析器?
- 如何找出如果你使用HTTPS没有$_SERVER['HTTPS']
- 更好的方法检查变量为null或空字符串?
- 当使用Composer的开发/生产开关时,如何正确部署?
- 自动删除Laravel (Eloquent ORM)中的相关行
- 在取消设置元素后重新设置数组键
- 如何修剪空白的数组值在php