php - 如何在 PHP 中删除文件
问题描述
我想删除 PHP 中特定目录中的文件。我怎样才能做到这一点?我有以下代码,但它不会删除文件。
$files = array();
$dir = dir('files');
while ($file = $dir->read()) {
if ($file != '.' && $file != '..') {
$files[] = $file;
}
unlink($file);
}
解决方案
我认为您的问题并不具体,此代码必须清除目录“文件”中的所有文件。
但是我认为该代码中有一些错误,这是正确的代码:
$files= array();
$dir = dir('files');
while (($file = $dir->read()) !== false) { // You must supply a condition to avoid infinite looping
if ($file != '.' && $file != '..') {
$files[] = $file; // In this array you push the valid files in the provided directory, which are not (. , ..)
}
unlink('files/'.$file); // This must remove the file in the queue
}
最后确保您提供了正确的 dir() 路径。
推荐阅读
- python - 从生成元组和单个值的生成器生成三元组
- next.js - Next.js 链接位置
- javascript - 获取具有多个路径的 svg 文件的单个路径值
- python - 在 Excel 或 Python 中按公共 ID 和值求和
- javascript - Azure 上的 WebGPU 部署
- svg - 背景图像 svg 不适用于 webpack
- reactjs - 用于 API 调用的 React componentDidMount 与 useEffect 挂钩
- html - 单击时更改切换按钮?
- vb.net - 如何使用 VB.Net 比较两个日期时间值而不是字符串
- java - 仅限 Android 应用程序的指纹身份验证