【问题标题】:The image cannot be displayed because it contains errors (php)图片无法显示,因为它包含错误(php)
【发布时间】:2020-02-20 18:22:44
【问题描述】:

我想显示存储在我的数据库中的图像,但我不断收到该错误。

图像作为 longblob 存储在我的数据库中。 我使用 upload.php 中的这段代码上传它:

<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
    Select image to upload:
    <input type="file" name="image" />
    <input type="submit" name="submit" value="UPLOAD" />
</form>
<?php
if (isset($_POST["submit"])) {
    $check = getimagesize($_FILES["image"]["tmp_name"]);
    if ($check !== false) {
        $image = $_FILES['image']['tmp_name'];
        $imgContent = addslashes(file_get_contents($image));

        /*
     * Insert image data into database
     */

        //Insert image content into database

        $insert = $pdo->query("UPDATE users SET image='".$imgContent."'"."WHERE id_user = ".$posts[0]->get_id());


        if ($insert) {
            echo "File uploaded successfully.";
        } else {
            echo "File upload failed, please try again.";
        }
    } else {
        echo "Please select an image file to upload.";
    }
}
?>

然后我尝试在 getImage.php 中显示它:

<?php

$id = $_GET['id'];
$query = $pdo->prepare('SELECT * FROM users WHERE username LIKE :us');
$query->bindValue(':us', $_SESSION['login'], PDO::PARAM_STR);
$query->execute();
$user = $query->fetchAll(PDO::FETCH_CLASS, "User");

header ('Content-Type: image/png');
echo $user[0]->get_image();
?>

当我转到 /getImage.php?id=1 时,出现错误

图片无法显示,因为它包含错误

我做错了什么?

【问题讨论】:

  • 你为什么在图片上使用addslashes?这将改变它并使其无法使用。由于它来自用户使用参数绑定,就像您在 getimage 中所做的那样,以防止出现问题
  • 首先确保您获得了有效的图像 blob 值,然后尝试添加 echo base64_encode($user[0]-&gt;get_image());
  • 你为什么不使用准备好的语句? addslashes 不足以防止 SQL 注入,更不适合二进制数据。
  • 我现在删除了 addlashes 并改用了准备好的查询。 echo base64_encode($user[0]->get_image());不幸的是什么也没做。 blob值也是有效的,因为我可以通过从数据库手动下载来查看图片
  • 您的代码实际上对我有用。 get_image() 到底在做什么?希望不是stripslashes

标签: php html sql image


【解决方案1】:

已解决:我在标题前添加了ob_end_clean();,它起作用了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-23
    • 2012-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-24
    相关资源
    最近更新 更多