从php文件显示图像(存储在mysql db中)

时间:2012-05-10 16:35:40

标签: php mysql

我正在尝试显示存储在mysql数据库中的图像。 我这样存储:

if (isset($_SESSION['mod']) && (isset($_GET['upload'])) ) {
    if (isset($_FILES['image'])  && $_FILES['image']['size'] > 0) { 

    $con = mysql_connect("localhost", "root");
    mysql_select_db("psi", $con);

      // Temporary file name stored on the server
      $tmpName  = $_FILES['image']['tmp_name'];  

      // Read the file 
      $fp      = fopen($tmpName, 'r');
      $data = fread($fp, filesize($tmpName));
      $data = addslashes($data);
      fclose($fp);

      //now i use <tmpName> as an actual name of file
      $tmpName  = $_FILES['image']['name'];  
      if (isset($_GET['name']))
        $tmpName = $_GET['name'];

        $uname = $_SESSION['uname'];
        $idObj = mysql_query("SELECT id_object AS id FROM tobject WHERE uname = '$uname'");
        $idObj = mysql_fetch_assoc($idObj);
        $idObj = $idObj['id'];

      // Create the query and insert
      // into our database.
      $query = "INSERT INTO slike ";
      $query .= "VALUES ('', '$idObj', '$data', '$tmpName')";
      $results = mysql_query($query, $con);

      // Print results
      print "Thank you, your file has been uploaded.";

}
else {
   print "No image selected/uploaded";
}

}

我想这没关系..它确实存储了db(适当的大小),但我无法手动查看它是什么..因此,当我尝试使用此代码获取它时:

else if (isset($_GET['idSlike'])) {
$idSlike = $_GET['idSlike'];

    $con = mysql_connect("localhost", "root");
    mysql_select_db("psi", $con);

$res = mysql_query("SELECT slika FROM slike WHERE id_slika = '$idSlike'");
if (!$res) {
    die("greska: " . mysql_error());
};

$slika = mysql_fetch_array($res);
$slika = $slika['slika'];
header('Content-Type: ' . $slika['mimetype']);
echo $slika;
}
  

注意:从db存储和获取图像都在同一个文件中   (image.php)...

我什么都没得到...... 我尝试用以下方式显示它:

<img src="image.php?idSlike=10"/>
  

我硬编码的id但它们存在于db

我也试过

echo "<img src=\"image.php?idSlike=13\">";

通过另一个php文件,但我得到的是一个空图像(正确的src)

我正在使用xampp(mysql 5.5.16; PHP 5.3.8)...

1 个答案:

答案 0 :(得分:1)

使用以下命令启用开发环境中的通知和警告:

ini_set("display_errors", 1);
error_reporting(E_ALL);

你正在做非敏感的事情(如果你允许,PHP会告诉你):

$slika = mysql_fetch_array($res);
$slika = $slika['slika'];
header('Content-Type: ' . $slika['mimetype']); // <-- $slika is a string not an array
echo $slika; // <-- if $slika is an array here, you can not echo is like this