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

PHP开发个人博客时图片无法保存到文件夹且前端不显示问题求助

问题修复方案

1. 修复表单文件上传属性(核心问题)

你把enctype="multipart/form-data"属性写到了文件选择input标签上,这个属性必须加在<form>标签上,否则浏览器不会传输文件二进制内容,后端自然拿不到上传的文件。
修复后的form标签代码:

<form action="addPost_form.php" method="post" class="row justify-content-center" enctype="multipart/form-data">

同时删掉input标签上的enctype='multipart/form-data'属性。

2. 修复新增文章逻辑的判断漏洞

当前代码如果标题长度<=2或者内容长度<=5,会直接清空$error变量,哪怕图片上传失败也不会提示,且就算文件上传失败依然会把$img写入数据库,修改逻辑如下:

<?php
session_start();
require_once '../DB.php';

$error = '';
$img = ''; // 先初始化img变量
if($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['button-post']))  {

    if (!empty($_FILES['img']['name'])){
        $img = time() . "_" . $_FILES['img']['name'];
        $fileTmpName = $_FILES['img']['tmp_name'];
        $fileType = $_FILES['img']['type'];
        $destination = "../img/" . $img;

        if (strpos($fileType, 'image') === false) {
            $error = "上传的文件不是图片!";
        }else{
            // 先检查目标文件夹是否存在,不存在就创建
            if (!is_dir('../img/')) {
                mkdir('../img/', 0755, true);
            }
            $result = move_uploaded_file($fileTmpName, $destination);
            if (!$result){
                $error = "图片上传到服务器失败,请检查img文件夹写入权限";
            }
        }
    }else{
        $error= "请选择要上传的图片";
    }

    $title = trim( $_POST['title']);
    $texton = trim( $_POST['texton']);

    if (strlen($title) <= 2 ) {
      $error = "标题长度不能少于3位";
    } elseif (strlen($texton)<= 5 )  {
      $error = "文章内容长度不能少于6位";
    }

    // 只有没有错误的时候才写入数据库
    if (empty($error)) {
        $sql = "INSERT INTO `posts`(`title`, `texton`, `img`) VALUES(?,?,?)";
        $query = $connect->prepare($sql);
        $query->execute([$title,$texton,$img]);
        // 提交成功跳转到首页
        header('Location: index.php');
        exit;
    }
}

3. 修复首页图片路径错误

当前img标签的src语法错误,多了多余的点和分号,修改为:

<img src="/img/<?= $row->img ?>" alt="postik">

4. 检查文件夹权限

确保项目根目录下的img文件夹有写入权限,Linux服务器可以执行以下命令设置权限:

chmod 755 /path/to/your/project/img
# 如果还是不行可以临时设777排查权限问题
chmod 777 /path/to/your/project/img

内容的提问来源于stack exchange,提问作者Макc

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 05:24:05