大家好,提前感谢!事情是,我有两个文件名为'test3.txt'和'text2.txt'在我的文件夹。我要做的是把它们都删除,把它们存储在一个数组中。首先,我检查文件是否存在'file_exists'方法,然后当我试图删除它们时,它失败了。我知道我做错了什么,但我做了一点研究,找不到这个问题的答案。如果可能的话,我要做的就是同时删除这两个文件。
1 <?php
2
3 $files = array('test3.txt', 'text2.txt');
4 $exists = false;
5
6 foreach ($files as $file) {
7 if (file_exists($file)) {
8 $exists = true;
9 }
10 }
11
12 if ($exists == true) {
13 unlink($files);
14 echo "Files were successfully deleted";
15 }
16 else {
17 echo "Couldn't delete files";
18 }
浏览器返回True,尽管文件仍然没有从目录中删除。下面是浏览器的输出:
Warning: unlink() expects parameter 1 to be a valid path, array given in /var/www/html/web/copy.php on line 13
Files were successfully deleted
unlink()
函数的文档清楚地表明,它需要一个字符串作为第一个参数,一个文件名。不是数组。
见http://php.net/manual/en/function.unlink.php
你可以尝试这样做,而不是手动遍历文件:
<?php
$files = ['test3.txt', 'text2.txt'];
array_map('unlink', $files);
我试过了…作品!)
我会简化一下…
<?php
$files = array('test3.txt', 'text2.txt');
foreach ($files as $file) {
if (file_exists($file)) {
unlink($file);
echo $file . " was successfully deleted";
}
else {
echo $file . " does not exist.";
}
}
您检查每个文件,但试图同时删除所有文件。您应该逐一解除每个文件的链接。
$files = array('test3.txt', 'text2.txt');
$exists = false;
foreach ($files as $file) {
if (file_exists($file)) {
$exists = true;
}
}
if ($exists == true) {
foreach($files as $file) {
unlink($file);
}
echo "Files were successfully deleted";
}
else {
echo "Couldn't delete files";
}
最好这样写:
foreach ($files as $file) {
if (file_exists($file)) {
unlink($file);
}
}
unlink($files);
—您发送数组,但不发送文件名。
foreach ($files as $file) {
unlink($file);
}
你这里还有一个问题:
foreach ($files as $file) {
if (file_exists($file)) {
$exists = true;
}
}
如果其中一个文件是存在的,则取$exists为真。试试这样写:
<?php
$files = array('test3.txt', 'text2.txt');
foreach ($files as $file) {
if (file_exists($file)) {
unlink($file);
}
}
echo "Files were successfully deleted";