我想从名为“ fajlovi”的文件夹中删除文件。多次删除和单次删除应该起作用。但是它将删除文件夹中的第一个文件(文件夹中文件数组中的0位置)。如果我检查任何文件,它将删除前4个文件,而不是我检查过的文件。这是代码:
$a = glob("fajlovi/*");
echo "<br>var_dump of \$a ------------------------<br><pre>";
var_export($a);
echo "</pre>end dump od \$a ------------------------<br><br>";
echo "Number od files in the directory: " . count($a) . "<br>";
echo "<form method='POST' action='" . $_SERVER['PHP_SELF'] . "'><table >";
echo "<th>File name:</th><th>Size MB:</th><th>Delete:</th>";
foreach ($a as $key => $value) {
echo "<tr><td>" . $value . "</td>";
echo "<td>" . round(filesize($value) / 1024 / 1024, 5) . " MB <br></td>";
echo "<td><input type='checkbox' name='checked[]'>" . $img_number = $key + 1 . "</td>";
}
echo "<tr><td colspan=3><input type='submit' name='delete' value='Delete'></td></tr>";
echo "</table></form>";
if (isset($_POST['delete'])) {
$checkbox = $_POST['checked'];
for ($i = 0; $i <= count($a); $i++) {
if (isset($checkbox[$i])) {
if (unlink($a[$i])) {
echo "Successfully deleted file" . $a[$i] . "<br>";
}
}
}
}
if (!empty($_POST['checked'])) {
var_dump($_POST['checked']);
}
1。这是页面的屏幕截图:
2。然后检查要删除的图像:
4。在再次进入页面后,我们可以看到删除了错误的图像:
您需要给您的输入值
<input type='checkbox' name='checked[]' value='{$key}'>
这里有一些代码可以使您朝正确的方向前进。
$files = glob('fajlovi/*');
$indicesToDelete = array_intersect($_POST['checked'] ?? [], array_keys($files));
foreach ($indicesToDelete as $index) {
if (unlink($files[$index])) {
echo "Successfully deleted file" . $files[$index] . "<br>";
}
}