从文件夹PHP删除图像 [英] delete image from folder PHP

查看:76
本文介绍了从文件夹PHP删除图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个保存图像的文件夹,名为img/.我有一张桌子,上面放着我所有的照片:

I have a folder where I keep my images, named img/. I have a table with all of my images:

<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".

How can I delete the image associated to the button with the value:"Delete image".

推荐答案

有一些路线.最简单的一种方法是将其变成一种形式.提交时,您对POST数据有反应,并使用unlink

There are a few routes. One, the most simple, would involve making that into a form; when it submits you react to POST data and delete the image using unlink

免责声明:这是不安全的.攻击者可能使用此代码删除服务器上的任何文件.您必须扩展此演示代码以添加某种安全措施,否则您可能会遇到坏事.

DISCLAIMER: This is not secure. An attacker could use this code to delete any file on your server. You must expand on this demonstration code to add some measure of security, otherwise you can expect bad things.

每个图像的显示标记都将包含如下形式:

Each image's display markup would contain a form something like this:

echo '<form method="post">';
  echo '<input type="hidden" value="'.$file.'" name="delete_file" />';
  echo '<input type="submit" value="Delete image" />';
echo '</form>';

...并在同一PHP文件的顶部:

...and at at the top of that same PHP file:

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请求,而不是提交表单.服务器端代码看起来与此类似.

You can elaborate on this by using javascript: instead of submitting the form, you could send an AJAX request. The server-side code would look rather similar to this.

文档和相关阅读内容

  • unlink - http://php.net/manual/en/function.unlink.php
  • $_POST - http://php.net/manual/en/reserved.variables.post.php
  • file_exists - http://php.net/manual/en/function.file-exists.php
  • array_key_exists - http://php.net/manual/en/function.array-key-exists.php
  • "Using PHP With HTML Forms" - http://www.tizag.com/phpT/forms.php

这篇关于从文件夹PHP删除图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆