我有一个文件夹,我保存我的图像,命名img/
.我有一张包含所有图像的表格:
<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>
Run Code Online (Sandbox Code Playgroud)
如何删除与按钮关联的图像,其值为:"Delete image"
.
Chr*_*ker 63
有几条路线.一个,最简单的,将涉及将其变成一种形式; 当它提交时你对POST数据作出反应并使用删除图像unlink
免责声明:这不安全.攻击者可以使用此代码删除服务器上的任何文件.您必须扩展此演示代码以添加一些安全措施,否则您可能会遇到不好的事情.
每个图像的显示标记都包含如下形式:
echo '<form method="post">';
echo '<input type="hidden" value="'.$file.'" name="delete_file" />';
echo '<input type="submit" value="Delete image" />';
echo '</form>';
Run Code Online (Sandbox Code Playgroud)
...并在同一个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...
Run Code Online (Sandbox Code Playgroud)
您可以使用javascript详细说明:您可以发送AJAX请求,而不是提交表单.服务器端代码看起来与此类似.
文件和相关阅读
unlink
- 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.phpmcr*_*yan 23
您可以使用该unlink()
功能删除PHP中的文件.
unlink('path/to/file.jpg');
Run Code Online (Sandbox Code Playgroud)
首先检查图像是否存在?如果是,则只需调用 unlink(您的文件路径) 函数即可删除您的文件,否则向用户显示消息。
if (file_exists($filePath))
{
unlink($filePath);
echo "File Successfully Delete.";
}
else
{
echo "File does not exists";
}
Run Code Online (Sandbox Code Playgroud)