我有一个文件夹来保存我的图像,名为 img/
。我有一张 table ,里面有我所有的图片:
<table border="3">
<tr>
<td>
<?php
$files = glob("img/*");
foreach ($files as $file) {
echo "<div class='divimages'>";
echo '<img src="'.$file.'"/>';
echo "<input type='submit' value='Delete image'/><br>";
echo "</div>";
}
?>
</td>
</tr>
</table>
如何删除与值为:"Delete image"
的按钮关联的图像。
最佳答案
有几条路线。一个,最简单的,就是把它变成一种形式;当它提交时,您对 POST 数据使用react并使用 unlink
免责声明:这是不安全的。攻击者可以使用此代码删除您服务器上的任何 文件。您必须扩展此演示代码以添加一些安全措施,否则您可能会遇到不好的事情。
每个图像的显示标记都包含如下形式:
echo '<form method="post">';
echo '<input type="hidden" value="'.$file.'" name="delete_file" />';
echo '<input type="submit" value="Delete image" />';
echo '</form>';
...并在同一个 PHP 文件的顶部:
if (array_key_exists('delete_file', $_POST)) {
$filename = $_POST['delete_file'];
if (file_exists($filename)) {
unlink($filename);
echo 'File '.$filename.' has been deleted';
} else {
echo 'Could not delete '.$filename.', file does not exist';
}
}
// existing code continues below...
您可以使用 javascript 对此进行详细说明:您可以发送 AJAX 请求而不是提交表单。服务器端代码看起来与此非常相似。
文档和相关阅读
取消链接
- http://php.net/manual/en/function.unlink.php$_POST
- http://php.net/manual/en/reserved.variables.post.phpfile_exists
- http://php.net/manual/en/function.file-exists.phparray_key_exists
- http://php.net/manual/en/function.array-key-exists.php- “将 PHP 与 HTML 表单结合使用” - http://www.tizag.com/phpT/forms.php
关于php - 从文件夹 PHP 中删除图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15005899/