You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP unlink()删除数据库关联文件夹图片失效问题求助

房源管理系统图片删除功能故障求助

我是PHP开发新手,当前正在开发房源管理应用,系统逻辑为以房屋地址命名文件夹,存储对应房源的全部图片,再将文件夹路径保存至数据库。目前开发「删除图片、同步更新数据库记录」功能时遇到问题,查阅大量网络资料仍未解决,具体情况如下:

  • displayImage($imgs, $pathimg)函数用于渲染展示每张图片及配套的删除按钮
  • 基于JavaScript编写的myimageDelete()函数运行正常,可将选中图片从前端页面移除
  • 基于PHP编写的phpUnlink($pathimg, $pic)函数执行失效,无法通过unlink()删除目标服务器图片
  • 尝试在JS函数中直接调用PHP函数的方案也未生效
  • 期望实现效果:点击删除后正常删除服务器存储的对应图片,同步更新服务器文件夹内容与数据库记录

相关实现代码

<?php
include './db.conn.php';
include './header.php';
?>

<?php
if (isset($_POST['save'])) {
  $address = $_POST['img_addr1'];
  $id = $_POST['prop_Id'];

  if (isset($path)) {
    $path1 = $pathimg;
    $total_img = scandir($path1);
    $sql = "UPDATE `list_tble` SET `img_addr`='$path1' WHERE prop_Id=$id";
    $stmt = $conn->prepare($sql);
    $stmt->execute();
  }
}
?>


<div class=" d-flex flex-column mx-auto bg-secondary mb-2" style="width: 500px; height:300px;">
  <div id="image_preview" class="bg-light w-100 h-20 d-flex  flex-wrap overflow-auto mb-2" style="border: 6px solid grey">
    <?php
    displayImage($imgs, $pathimg);

    ?>
  </div>
</div>
</div>

<?php
function displayImage($imgs, $pathimg)
{
  if (count($imgs) > 2) {
    foreach (array_splice($imgs, 2) as $pic) {
      echo '<form method="POST" id="small_img" class="dis_Image bg-warning mx-auto d-flex flex-column" style="width: 120px; height: 120px;">    <img src ="' . $pathimg . '/' . $pic . '" width="120px" height="120px" style="border:2px solid white" alt="House list image" />
      <input name="img_del" type="text" class="spanImage w-100 bg-danger fw-bold mx-auto" 
            style="cursor: pointer; color: white; font-size= 18px;" 
            onclick="myimageDelete()" value="DELETE" /> 
            </form>';
    }
  } else {
    echo "Directory is Empty.";
  }
}
?>

<?php
function phpUnlink($pathimg, $pic)
{
  if (isset($_POST['img_del'])) {
    $imgToUnlink = $pathimg . '/' . $pic;
    if (!unlink($imgToUnlink)) {
      echo "$imgToUnlink is not deleted";
    } else {
      echo "$imgToUnlink is deleted";
    }
  }
}
?>

<script type='text/javascript'>
  function myimageDelete() {
    event.target.parentNode.remove();    
  }
</script>

<?php
include './footer.php';
?>

内容的提问来源于stack exchange,提问作者TonyId

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 05:48:28