LinuxQuestions.org
Download your favorite Linux distribution at LQ ISO.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 05-09-2011, 10:17 AM   #1
matiasar
Member
 
Registered: Nov 2006
Location: Argentina
Distribution: Debian
Posts: 321
Blog Entries: 1

Rep: Reputation: 31
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 ).

Regards,
Matías
 
Old 05-09-2011, 01:05 PM   #2
Guttorm
Senior Member
 
Registered: Dec 2003
Location: Trondheim, Norway
Distribution: Debian and Ubuntu
Posts: 1,453

Rep: Reputation: 446Reputation: 446Reputation: 446Reputation: 446Reputation: 446
Hi

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

Last edited by Guttorm; 05-09-2011 at 01:11 PM.
 
Old 05-09-2011, 02:08 PM   #3
matiasar
Member
 
Registered: Nov 2006
Location: Argentina
Distribution: Debian
Posts: 321

Original Poster
Blog Entries: 1

Rep: Reputation: 31
Guttorm,

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.
 
Old 05-09-2011, 03:01 PM   #4
Guttorm
Senior Member
 
Registered: Dec 2003
Location: Trondheim, Norway
Distribution: Debian and Ubuntu
Posts: 1,453

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

wget --server-response http/localhost/displaypic.php?imgid=35
 
Old 05-10-2011, 08:48 AM   #5
matiasar
Member
 
Registered: Nov 2006
Location: Argentina
Distribution: Debian
Posts: 321

Original Poster
Blog Entries: 1

Rep: Reputation: 31
Guttorm,

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.
 
Old 05-10-2011, 08:33 PM   #6
matiasar
Member
 
Registered: Nov 2006
Location: Argentina
Distribution: Debian
Posts: 321

Original Poster
Blog Entries: 1

Rep: Reputation: 31
Guttorm,

Well, this is the result of:

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

Code:
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.
 
  


Reply

Tags
blob, image, mysql, php



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
Linux program to share pictures online, via Apache and PHP amonamarth Linux - Software 2 05-09-2011 06:44 PM
PHP: How can variables stored in a blob field, and then have them populated later? abefroman Programming 9 11-23-2009 09:16 AM
php question, how do I get a return from a field within a field? cherrington Programming 11 04-29-2009 01:27 AM
Centos 5.2 running Apache 2 and PHP 4 cannot display info.php codenjanod Linux - Server 2 08-19-2008 02:00 AM
Can not insert word file into mysql table (in blob field) prabhatsoni Linux - Software 2 07-21-2006 05:01 AM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

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

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration