-   Programming (
-   -   PHP+Apache: Problem trying to display BLOB field pictures (

matiasar 05-09-2011 11:17 AM

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.


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"]));

                                                  $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);
                                                catch (Exception $e)
                                                        echo "Se ha producido un error al insertar la imagen <br />";
                                                        // echo "verbose: " .$e->getmessage() ."<br/>";
                                                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:


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:


    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->bindColumn(1, $header_type, PDO::PARAM_STR);
              $stmt->bindColumn(2, $image, PDO::PARAM_LOB);
                header("Content-Type: ".$header_type);
                echo $image;

                // Debug
                $fh = fopen("/tmp/testimg.png", "wb");
                fwrite( $fh, stripslashes($image) );
                $fh = fopen("/tmp/displaypic.log", "w");
                fwrite($fh, $header_type."\n");
                fwrite($fh, "image data size strlen=" .strlen($image) ."\n");

              $stmt = null;
              $dbh = null;

Then to try to show the pic e call displaypic.php passing through GET the image's id:


<title>Testing show pic</title>
<p>Just a test:</p>
<p><img src="displaypic.php?imgid=<?php print $id;?>" /></p>

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 ).


Guttorm 05-09-2011 02:05 PM


What is "/tmp/testimg.png" and "/tmp/displaypic.log"? It should be a PNG file and the MIME type.

Edit, also:

PHP Code:

$imagen addslashes(fread($fh,filesize($_FILES["archivo"]["tmp_name"]))); 

Drop the addslashes:

PHP Code:

$imagen file_get_contents($_FILES["archivo"]["tmp_name"]); 

matiasar 05-09-2011 03:08 PM


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.

Guttorm 05-09-2011 04:01 PM

Hmm. Did you empty the browser cache? What is the output of this command:

wget --server-response http/localhost/displaypic.php?imgid=35

matiasar 05-10-2011 09:48 AM


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.

matiasar 05-10-2011 09:33 PM


Well, this is the result of:

wget --server-response http://localhost/.../displaypic.php?imgid=5


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:

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.

All times are GMT -5. The time now is 11:12 PM.