PHP+Apache: Problem trying to display BLOB field pictures
ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
PHP+Apache: Problem trying to display BLOB field pictures
I've been stuck for someday trying to solve this problem. Still I doesn't find the clue.
I'm writing a simple blog with PHP and mysql. I'm uploading images files through form and storing them in a BLOB field:
This is the main fragment, I'm using PDO extension.
Code:
if ( $_FILES["archivo"]["error"] === 0 && $_FILES["archivo"]["size"] > 10 && $_FILES["archivo"]["size"] < 900000 && strpos($_FILES["archivo"]["type"], "image") !== false )
{
// opening temp file
$fh = fopen($_FILES["archivo"]["tmp_name"],"rb") or die ("Error no pudo abrirse el archivo temporal.<br />");
$imagen = addslashes(fread($fh,filesize($_FILES["archivo"]["tmp_name"])));
//$imagen = fread($fh,filesize($_FILES["archivo"]["tmp_name"]));
fclose($fh);
try
{
$stmt = $dbh->prepare('INSERT INTO sblog_post_pics SET blog_post_id=?, filename=?, filesize=?, imgdata=?, type=?');
$stmt->bindParam(1, $lastInId, PDO::PARAM_INT);
$stmt->bindParam(2, $_FILES["archivo"]["name"], PDO::PARAM_STR, 255);
$stmt->bindParam(3, $_FILES["archivo"]["size"], PDO::PARAM_INT);
$stmt->bindParam(4, $imagen, PDO::PARAM_LOB);
$stmt->bindParam(5, $_FILES["archivo"]["type"], PDO::PARAM_STR, 50);
$stmt->execute();
}
catch (Exception $e)
{
echo "Se ha producido un error al insertar la imagen <br />";
// echo "verbose: " .$e->getmessage() ."<br/>";
}
unset($imagen);
}
else
{
echo "Error: hubo algun problema con la imagen suministrada.<br />Recuerde que el archivo debe ser menor a 900 kb.<br />Los tipos de archivos permitidos son gif, jpeg y png.";
}
This is the table structure where image data is stored:
Code:
mysql> describe sblog_post_pics;
+--------------+--------------+------+-----+-------------------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------+--------------+------+-----+-------------------+-------+
| blog_post_id | int(11) | NO | | 0 | |
| filename | varchar(255) | NO | | | |
| filesize | int(14) | NO | | 0 | |
| imgdata | mediumblob | NO | | NULL | |
| type | varchar(50) | NO | | | |
| timestmp | timestamp | NO | | CURRENT_TIMESTAMP | |
+--------------+--------------+------+-----+-------------------+-------+
imgdata is the blob field, and type is the mime-type, which I use later in header.
Code for storing the image seems to work ok. Put I can't get image shown. The code I used for this is the following:
displaypic.php
Code:
<?php
require '../../include/blg_conn_params.php';
$inId = $_GET["imgid"];
$dbh = new PDO('mysql:host=' .$blg_host .';dbname=' .$blg_bd, $blg_usuario, $blg_sena) or die ("No se pudo conectar a BD! de pics");
$stmt = $dbh->prepare('SELECT type, imgdata FROM sblog_post_pics WHERE blog_post_id=? ORDER BY blog_post_id DESC');
$stmt->bindParam(1,$inId, PDO::PARAM_INT);
$stmt->execute();
$stmt->bindColumn(1, $header_type, PDO::PARAM_STR);
$stmt->bindColumn(2, $image, PDO::PARAM_LOB);
$stmt->fetch(PDO::FETCH_BOUND);
header("Content-Type: ".$header_type);
echo $image;
// Debug
$fh = fopen("/tmp/testimg.png", "wb");
fwrite( $fh, stripslashes($image) );
fclose($fh);
$fh = fopen("/tmp/displaypic.log", "w");
fwrite($fh, $header_type."\n");
fwrite($fh, "image data size strlen=" .strlen($image) ."\n");
fclose($fh);
$stmt = null;
$dbh = null;
?>
Then to try to show the pic e call displaypic.php passing through GET the image's id:
Code:
<?php
$id="35";
?>
<html>
<head>
<title>Testing show pic</title>
</head>
<body>
<p>Just a test:</p>
<p><img src="displaypic.php?imgid=<?php print $id;?>" /></p>
</body>
</html>
I found within a lot of blogs, and code is very similar... But I can't get picture showed.
I was wondering if could be an specific apache issue... Something extra needed to be sent within http header? I don't know... Any suggestion will be very appreciated.
I'm using Debian (Lenny), PHP 5.3 and Apache 2 (apache2 - 2.2.9-10+lenny8 ).
Thanks for your reply.
Really, I tried with and without addslashes function with the same result...
Both files testimg.png and displaypic.log are just for testing porpouses, testimg.png is just a file written with the image data from the blob field, just to check if the data stored is ok. And that file seems to be ok, image is good.
Thanks!
At job, I swithed my application to work storing pics in filesystem just for not to delay development. But at home I left my old version, tonight I'll try the wget test you passed me, and I'll let you know.
I had made some tests with wget, but I didn't include --server-response that's interesting.
Petición HTTP enviada, esperando respuesta...
HTTP/1.1 200 OK
Date: Wed, 11 May 2011 01:12:33 GMT
Server: Apache/2.2.16 (Debian)
X-Powered-By: PHP/5.3.3-7
Connection: close
Content-Type: image/jpeg
Longitud: no especificado [image/jpeg]
Saving to: `displaypic.php?imgid=5'
Content-Type seems to be ok, right?
If I do file command to the data saved by wget I get:
Code:
matias@retux:~$ file displaypic.php\?imgid\=5
displaypic.php?imgid=5: data
And if I try to open that file with firefox it says that image contains error. The same occurs if I do: http://localhost/.../displaypic=imgid=5 from Firefox.
I've just found that downloaded file through wget is 1 byte bigger than the original image. I compared both files with: od -t x1 and in the beggining of downloaded file (the one using Blob) appears 0x0a as first character. Is it a LF character?
Really, that could be the reason, but still I don't find from where that character could come.
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.