【问题标题】:Attempting to display an image in PHP from a MySQL database尝试在 PHP 中显示 MySQL 数据库中的图像
【发布时间】:2011-12-09 00:24:53
【问题描述】:

我尝试通过以下代码使用 PHP 显示图像

<?php
header('Content-type: image/png');
 $port = "*";
 $server = "*:".$port;
 $dbname ="*";
 $user = "*";

 $conn = mysql_connect ("$server", "$user", "$pass") or die ("Connection
 Error or Bad Port");

mysql_select_db($dbname) or die("Missing Database");


    $speakerPic = $_POST['speakerPic'];
    $query = "SELECT Speaker.speaker_picture AS image FROM  Speaker JOIN Contact c USING(contact_id) 
    WHERE c.lname = '";
    $query .= $speakerPic."';";


$result = mysql_query($query,$dbname); 
$result_data = mysql_fetch_array($result, MYSQL_ASSOC);

echo $result_data['image'];   
?>

我不断收到此错误,图像“.../query2.php”无法显示,因为它包含错误。

很抱歉一直打扰你们,但是谁能告诉我问题出在哪里?

【问题讨论】:

  • 当心来自包含脚本的任何输出。确保消除 标记之外的任何内容。事实上,你应该完全删除你的结束 ?> 标签,以确保它后面没有空格。确保您的脚本没有回显某种错误消息。
  • 这些错误究竟是什么?
  • 使用浏览器的开发者工具查看图片的 HTTP 请求。特别注意Content-Length 标头。看看这是否不同于几个不同图像的图像大小(我假设你已经知道)。如果不一样,差别有多大?不同图像的差异是相同的还是保持不变?
  • 尝试跟踪你的 php 错误日志。
  • 另外,你的代码容易受到SQL injection的攻击。

标签: php mysql html


【解决方案1】:

不会说谎,OP 代码有很多不好的地方。

  1. 您应该通过 id 从数据库中提取图像,而不是某些字符串
  2. 您没有清理查询中使用的 var
  3. 如果默认图片不存在,您就不会提供默认图片
  4. 另外,我建议将文件 uris 存储在您的数据库中,而不是实际的图像 (blob)。您应该在文件系统上存储指向图像的指针。

不会过多地清理代码,只是让它变得不那么糟糕。我会建议一些类似的东西(未经测试):

// Utility.php
class Utility
{
    /**
     *
     * @param mixed $id is abstract, could be name or an actual id
     * @return string?
     */
    public static function getImage($id)
    {
        try {
            $port = "*";
            $server = "*:".$port;
            $dbname ="*";
            $user = "*";

            $conn = mysql_connect ("$server", "$user", "$pass");

            if (!$conn) {
               throw new Exception("Connection Error or Bad Port");
            }

            if (!mysql_select_db($dbname)) {
                throw new Exception("Missing Database");
            }

            $query = "SELECT Speaker.speaker_picture AS image FROM  Speaker JOIN Contact c USING(contact_id) WHERE c.lname = " . mysql_real_escape_string($id). ";";

            $result = mysql_query($query,$dbname); 
            $result_data = mysql_fetch_array($result, MYSQL_ASSOC);

            if (!isset($result_data['image'])) {
                throw new Exception('Image not found');
            }

            echo $result_data['image'];

         } catch Exception($e) {

             error_log($e->getMessage();

             return file_get_contents('/path/to/some/default/image.png');
         }   
    }
}

// image.php
require_once 'Utility.php';

header('Content-type: image/png');
ob_start();
Utility::getImage($_POST['speakerPic']);
$image = ob_get_flush();

echo $image;

【讨论】:

  • 谢谢。我绝对是一个初学者,我会试着绕着你的代码转。非常感谢您抽出宝贵的时间,这个社区很棒。
  • @user1087799:不用担心......并不是要给人一种过于苛刻的印象。
猜你喜欢
  • 2021-09-07
  • 2020-06-22
  • 2020-05-19
  • 2012-01-10
  • 1970-01-01
  • 2016-09-01
  • 2015-10-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多