例如,我有一个名为“Temp”的文件夹,我想使用PHP删除或刷新该文件夹中的所有文件。我可以这样做吗?
当前回答
在PHP中删除文件夹中的所有文件的简单和最好的方法
$files = glob('my_folder/*'); //get all file names
foreach($files as $file){
if(is_file($file))
unlink($file); //delete file
}
从这里得到这个源代码- http://www.codexworld.com/delete-all-files-from-folder-using-php/
其他回答
我更新了@Stichoza的答案,通过子文件夹删除文件。
function glob_recursive($pattern, $flags = 0) {
$fileList = glob($pattern, $flags);
foreach (glob(dirname($pattern).'/*', GLOB_ONLYDIR|GLOB_NOSORT) as $dir) {
$subPattern = $dir.'/'.basename($pattern);
$subFileList = glob_recursive($subPattern, $flags);
$fileList = array_merge($fileList, $subFileList);
}
return $fileList;
}
function glob_recursive_unlink($pattern, $flags = 0) {
array_map('unlink', glob_recursive($pattern, $flags));
}
这是一个简单的方法和很好的解决方案。试试这段代码。
array_map('unlink', array_filter((array) array_merge(glob("folder_name/*"))));
$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);
下面是一种使用标准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);
}
}
在PHP中删除文件夹中的所有文件的简单和最好的方法
$files = glob('my_folder/*'); //get all file names
foreach($files as $file){
if(is_file($file))
unlink($file); //delete file
}
从这里得到这个源代码- http://www.codexworld.com/delete-all-files-from-folder-using-php/
推荐文章
- 在PHP单元测试执行期间,如何在CLI中输出?
- 在PHP中使用heredoc的优势是什么?
- 如何将文件指针(file * fp)转换为文件描述符(int fd)?
- PHP中的echo, print和print_r有什么区别?
- 如何将XML转换成PHP数组?
- 如何将对象转换为数组?
- 从IP地址获取位置
- 获取数组值的键名
- HTTPS和SSL3_GET_SERVER_CERTIFICATE:证书验证失败,CA is OK
- PHP -获取bool值,当为false时返回false
- 如何删除文件中的特定行?
- 在foreach中通过引用传递
- 如何触发命令行PHP脚本的XDebug分析器?
- 如何找出如果你使用HTTPS没有$_SERVER['HTTPS']
- 更好的方法检查变量为null或空字符串?