如何使用PHP显示存储在MySQL中的图像?

时间:2015-04-07 06:49:42

标签: php mysql

我想用PHP显示来自MySQL的图片。我写了代码,但显示错误消息 ((图片“http://localhost/abshaaz/ViewImage.php”无法显示,因为它包含错误)),背景颜色变为黑色。如果我使用If()函数,它将显示程序的else部分,这是一条错误消息:“正在加载图像类型错误!” 这是代码,请有人帮我找出错误: 但在此之前,我个人怀疑header()函数,因为当删除它时会显示非格式或非类型图像(笨重的不可读代码),但每当放回时都会发生上述错误。

  • 数据库名称: abshaaz
  • 表名: photoalbum
  • 列名: ImageID,ImageName,ImageFile

`

<?php

mysql_connect("127.0.0.1", "root","");
mysql_select_db("abshaaz");


if(isset($_GET['ImageID']))
{

    $imageid=mysql_real_escape_string($_GET['ImageID']);
    $query=mysql_query("SELECT * FROM photoalbum WHERE ImageID='$imageid'"); 

    while($row=mysql_fetch_assoc($query))

    {
      $imageData= $row["ImageFile"];

    }
      header("Content-type: image/jpeg");

      echo $imageData;
}
else 
{
    echo "loading image type error!";   
}

?>`

然后我在另一页中使用下面的图像标签来调用图像

<img src="ViewImage.php?ImageID=5" width=100 height=100>

3 个答案:

答案 0 :(得分:0)

存储照片的最佳做法是在文件系统中。您应该将照片保存在文件夹中并将文件名保存在数据库中。 例如: 如果图像文件夹中的image.jpg名称保存图像,则必须在图像文件夹中保存此“image.jpg”的名称。

<?php

mysql_connect("127.0.0.1", "root","");
mysql_select_db("abshaaz");


if(isset($_GET['ImageID']))
{

    $imageid=mysql_real_escape_string($_GET['ImageID']);
    $query=mysql_query("SELECT * FROM photoalbum WHERE ImageID='$imageid'"); 

$imageData = array();

    while($row=mysql_fetch_assoc($query))

    {
      $imageData[] = $row["ImageFile"];

    }
      //header("Content-type: image/jpeg");

      //echo $imageData;
foreach($imageData as $image) {
  echo "<img src=\"$image['ImageFile']\" />";
 }
}
else 
{
    echo "loading image type error!";   
}

?>`

答案 1 :(得分:0)

我使用mysqli而不是mysql编写了这个答案,这个答案会根据请求将图像返回给浏览器,或者如果遇到错误则返回404找不到的文件。它还会将错误记录到文件中以供管理员检查。

此代码将根据图像ID在数据库中查询服务器上图像的绝对路径和文件名。它还将验证输入并在执行数据库查询之前对其进行过滤。

在成功查询后,它会检查文件是否仍然存在于服务器上,然后再读取文件内容并使用jpeg标头将其回显到浏览器。

<?php

include 'database_settings.php';

$mysqli = @new mysqli ( $mysql_hostname, $mysql_username,
    $mysql_password, $mysql_database );

if ( $mysqli->connect_errno > 0 ) {
    header ( $_SERVER [ 'SERVER_PROTOCOL' ] . ' 404 Not Found' );
    file_put_contents ( 'path/to/error.log', 'There was an error connecting to the database in file ' .
        __FILE__ . PHP_EOL, FILE_APPEND );

    return; // quit execution of the file
}

if ( ( isset ( $_GET [ 'ImageID' ] ) ) && ( ctype_digit ( $_GET [ 'ImageID' ] ) ) ) {

    $query = $mysqli->query ( sprintf ( "SELECT * FROM photoalbum WHERE ImageID=%d",
        $mysqli->real_escape_string ( $_GET [ 'ImageID' ] ) ) );

    if ( $query->num_rows > 0 ) {
        $filename = null;

        while ( $row = $query->fetch_assoc () ) {
            $filename = $row [ 'ImageName' ];
        }

        if ( isset ( $filename ) ) {
            if ( file_exists ( $filename ) ) {
                header("Content-type: image/jpeg");
                print file_get_contents ( $filename );
            } else {
                file_put_contents ( 'path/to/error.log', 'There was an locating the image ' . $filename .
                   ' on the server filesystem in file ' .
                    __FILE__ . ' on line ' . __LINE__ . PHP_EOL, FILE_APPEND );
                header ( $_SERVER [ 'SERVER_PROTOCOL' ] . ' 404 Not Found' );
            }
        } else {
            file_put_contents ( 'path/to/error.log', 'There was an error getting an image filename from the database with an id of ' .
                $_GET [ 'ImageID' ] . ' in file ' . __FILE__ . ' on line ' . __LINE__ . PHP_EOL, FILE_APPEND );
            header ( $_SERVER [ 'SERVER_PROTOCOL' ] . ' 404 Not Found' );
        }
    } else {
        file_put_contents ( 'path/to/error.log', 'There was an error getting an image filename from the database with an id of ' .
            $_GET [ 'ImageID' ] . ' in file ' . __FILE__ . ' on line ' . __LINE__ . PHP_EOL, FILE_APPEND );
        header ( $_SERVER [ 'SERVER_PROTOCOL' ] . ' 404 Not Found' );
    }

    $query->close (); // free the result from memory
} else {
    // no error needs to be logged
    header ( $_SERVER [ 'SERVER_PROTOCOL' ] . ' 404 Not Found' );
}

$mysqli->close (); // close the database connection

// EOF

答案 2 :(得分:0)

我通常不喜欢在帖子中添加第二个答案,所以我很抱歉。 如果这个有帮助,我会删除我的其他答案。

文件名:ImageHandler.php

<?php

class ImageHandler
{
    public function __construct ( mysqli $mysqli ) {
        $this->mysqli = $mysqli;
    }

    public function InsertImage ( $filename ) {
        $absolute_filename = realpath ( $filename );
        if ( $absolute_filename === true ) {
            if ( $this->mysqli->query ( sprintf ( 'INSERT INTO album (\'filename\') VALUES (\'%s\')', $absolute_filename ) ) ) {
                return $this->mysqli->insert_id;
            }
            throw new Exception ( 'There was an error inserting the image into the database.' );
        }
        throw new Exception ( 'Image "' . $filename . '" could not be found on the server.' );
    }

    public function GetImage ( $imageID ) {
        if ( ( is_integer ( $imageID ) == false ) || ( $imageID < 1 ) ) {
            throw new InvalidArgumentException ('The image ID must be an integer greater than 0' );
        }
        $query = $mysqli->query ( sprintf ( 'SELECT * FROM album WHERE id=%d', $imageId ) );
        if ( $query->num_rows > 0 ) {
            $filename = null;
            while ( $row = $query->fetch_assoc () ) {
                $filename = $row [ 'filename' ];
            }
            $query->close ();
            if ( isset ( $filename ) ) {
                $absolute_filename = realpath ( $filename );
                if ( $absolute_filename === false ) {
                    throw new Exception ( 'Image "' . $filename . '" could not be found on the server.' );
                }
                return $absolute_filename;
            }
            throw new Exception ( 'There was an error returning the image filename from the database.' );
        }
        $query->close ();
        throw new Exception ( 'There was an error getting an image filename from the database with an image id of [' . $imageId . '].' );
    }

    public function PrintImage ( $filename ) {
        $absolute_filename = realpath ( $filename );
        if ( $absolute_filename === false ) {
            throw new Exception ( 'Image "' . $filename . '" could not be found on the server.' );
        }
        header ( 'Content-Type: image/jpeg' );
        print file_get_contents ( $absolute_filename );
    }

    private $mysqli;
}

?>

用于将图像打印到浏览器的示例。

在开始之前,我们将对服务器目录结构做一些假设。 ImageHandler.php存储在image.php旁边,包含所有图像的受保护图像文件夹位于父文件夹的一个目录中,Web浏览器无法访问,位于images文件夹旁边的是一个名为logs的文件夹。

image.php

<?php

try {
    if ( isset ( $_GET [ 'id' ] ) == false ) {
        header ( $_SERVER [ 'SERVER_PROTOCOL' ] . ' 404 Not Found' );
        return;
    }
    include 'ImageHandler.php';
    include 'database_settings.php';
    $mysqli = @new mysqli ( $mysql_hostname, $mysql_username, $mysql_password, $mysql_database );
    if ( $mysqli->connect_errno > 0 ) {
        throw new Exception ( 'There was an error connecting to the database.' );
    }
    $image = new ImageHandler ( $mysqli );
    $filename = $image->GetImage ( $_GET [ 'id' ] );
    $image->PrintImage ( $filename );
} catch ( Exception $e ) {
    header ( $_SERVER [ 'SERVER_PROTOCOL' ] . ' 404 Not Found' );
    file_put_contents ( '../logs/error.log', $e->getMesage() . ' in file ' . $e->getFile() . ' on line ' . $e->getLine (). PHP_EOL, FILE_APPEND );
}

?>

要将信息存储到数据库中,我建议将此文件放在受密码保护的登录后面,图像需要已经位于images文件夹内

saveimage.php

<?php

try {
    if ( isset ( $_POST [ 'filename' ] ) == false ) {
        throw new Exception ( 'Please complete this form to add an image to the database.' );
    }
    $path = realpath ( '../images' );
    if ( $path === false ) {
        throw new Exception ( 'Images path does not exist.' );
    }
    $path .= DIRECTORY_SEPARATOR . $_POST [ 'filename' ];
    include 'ImageHandler.php';
    include 'database_settings.php';
    $mysqli = @new mysqli ( $mysql_hostname, $mysql_username, $mysql_password, $mysql_database );
    if ( $mysqli->connect_errno > 0 ) {
        throw new Exception ( 'There was an error connecting to the database.' );
    }
    $image = new ImageHandler ( $mysqli );
    $id = $image->InsertImage ( $path );
    print 'Image saved as ID ' . $id . '<br><br><img src="image.php?id=' . $id .'"/>';
} catch ( Exception $e ) {
    // form would go here and $e->getMessage() would be used to display messages to the browser
}

?>