php目录读取并删除现有文件
我试图确保当用户上传个人资料图片时,目录“profile_pic”中只能有一张图像。我正在使用 while 循环打开并读取目录,但 @unlink 不起作用。下面是php代码:
$directory = "uploads\\".$id."\images\profile_pic\\";
if (glob($directory . "*.jpg") != false) {
$filecount = count(glob($directory . "*.jpg"));
if ($filecount > 0) {
//delete exiting pics in folder profile_pic
$handle = opendir($directory);
while ($handle && ($file = readdir($handle)) !== false) {
if ( unlink($entry)) {
$msg .= "File Deleted";
}
}
closedir($directory);
}
}
I am trying to make sure that when the user uploads a profile picture, there can only be one image within the dir "profile_pic". I am openning and reading the dir with a while loop but the @unlink is not working. Below is the php code:
$directory = "uploads\\".$id."\images\profile_pic\\";
if (glob($directory . "*.jpg") != false) {
$filecount = count(glob($directory . "*.jpg"));
if ($filecount > 0) {
//delete exiting pics in folder profile_pic
$handle = opendir($directory);
while ($handle && ($file = readdir($handle)) !== false) {
if ( unlink($entry)) {
$msg .= "File Deleted";
}
}
closedir($directory);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
抱歉,您在哪里定义了
$entry
- 您是否曾为其分配过值?为什么要对glob()
进行两次完全相同的调用,而不是在变量中捕获第一次调用的结果?当您已经通过glob()
编辑并获得了文件列表时,为什么还要费力地使用opendir()
来列出文件呢?特别是当您不对要删除的文件应用相同的*.jpg
过滤器时...只需执行以下操作:
Sorry, where did you define
$entry
- did you ever assign a value to it? And why do you make exactly the same call toglob()
twice instead of catching the result of the first call in a variable? And why bother toopendir()
to list files when you have alreadyglob()
ed and obtained that list of files? Especially when you don't apply the same*.jpg
filter to the files you are deleting...Just do this: