PDO to retrieve and display images without creating files - php

Trying to loop through a test database with images (I know many say not to do this, but it simplifies so much in terms of backups, etc.). I can get the result I want by creating image files on the fly, but there must be a way to do this without creating files. Can someone suggest a syntax I can use without having to create these image files?
Here is what I have working:
<?php
// configuration
$dbhost = "localhost";
$dbname = "test";
$dbuser = "root";
$dbpass = "";
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
// query
$sql = "SELECT id,title,author,description,cover FROM books";
$q = $conn->prepare($sql);
$q->execute();
$q->bindColumn(1, $id);
$q->bindColumn(2, $title);
$q->bindColumn(3, $author);
$q->bindcolumn(4, $description);
$q->bindColumn(5, $cover, PDO::PARAM_LOB);
while($q->fetch())
{
file_put_contents($id.".png",$cover);
echo ("<img src='".$id.".png'><br />, $title, $author, $description,<br/>");
}
?>
I am thinking that we should be able to eliminate the "file_put_contents.." line and in the echo line, replace the
<img src='".$id.".png'>"
with some php/pdo statement that retrieves the blob and puts it in the proper format. Tried a few things, but have not been successful.
Any suggestions would be helpful!

you do not need to do it in 2 separate files and invoke the script in src attribute of img tag.
Try do this
echo '<img src="data:image/'.$type.';base64,'.base64_encode($image).'"/>';
Where $type is the extension of the image(.png/.jpeg/....) and $image is the binary of the image that you have stored in your DB. in my case I pull the value of the type of image from the db, if you store always the same extension(ex jpeg) you can simply write:
echo '<img src="data:image/jpeg;base64,'.base64_encode($image).'"/>';
the method is an alternative to do that with 2 files.

You need to write code in 2 files. As when browser gets <img src="path/to img_file"> code (or code like <script src="....">), etc, a separate request is sent to server by browser at src path value. So, you also need to create file img_file.
Pseudo code is below,
Firstfile.php
<?php
..................... Other code
while($q->fetch())
{
?>
<img src="image.php?id=<?php echo $id; ?>"><br />,
<?php
echo "$title, $author, $description<br/>";
}
?>
And at image.php file,
header('Content-Type: image/png');
$id = $_GET['id'];
$query = " ..... where id = '".$_GET['id']."'";
//You need error handling if $_GET['id'] is integer and valid value. I am not writing this error handling code
if($q->row_count!=1){
//no database row found. It's error.
echo "Show no image found image. As browser expects image you can not write text here";
die;
}
//it's valid image, else code is already terminated by above die.
while($q->fetch())
{
//show image
echo $cover;
}
?>
I wrote Pseudo code exact code depend on requirements.
If you want .png extension, you can use Apache rewrite. Google it you will get it.
When first time i wrote answer, I missed last php ending tag. By the way, last ending tag ?> is optional in php.
If you are getting X , it seems first file code is ok. As imag_file is not at server, it's showing 404 error. View source to check whether $_GET['id'] is correct. If id is correct, then you want to write at file img_file.php

Related

Displaying images stored in a database using PHP

For my current assignment I'm trying to store files into the DB and display them. Currently I have no problem storing the files but I can't display them properly. I'm using this in my main form.
<td><a href=getImage.php?id='.$file[0].'" />Resume</a></td>
And this is the query I'm using to get the file out of the DB.
$sql = "SELECT file FROM table WHERE Res_ID=$referenced_ID";
$result = mysqli_query($dbc, $sql);
$row = mysqli_fetch_assoc($result);
header('Content-type: image/jpg');
echo "<img src=\"{$row['file']}\" /><br />";
The result is
…³V!µÔ¢ošweöÿZ–îÌèEÈÎpEJ·˜kä€òþòâ­Gas
È*G¨¥vA¤uEN¤S]‰:ñY“iwØ8‡¥e]ØÝGÑ‘øQÍ!«3¨ÄvÙÁu§]zÕÿOã^ssÌuáY7WP“ÔT6Æà™ëâþÊQË!üi­oe8
9ô5ã?ÛSÇÔ‘RÃ⛘VCBh¹>ϳ=BïÃVwåçÔW#¯|8†ufŠ4ob1PiÞ=q(,>µÐYx®Æ÷¥ò›Ñ5b½äy6«ðÆbͲϡ®fóá–
í„ξ‹’xvîYVEöæ«6§]|²½ýj‡Ï#åËßjv™-k.u\ŠÈ›O–#ó!ЊúÊmcLþ-¹ïšÆÔ4ïkùñE¸ÿ0h±j§‘òù
Ԉ켯íº×ÂÝã/g:»¸âïþ=³-²û?áHÑI3ŒKÙW¨ÍNºŽî-¶_Ã#IÙ¸{Tiû¸>â€3ÿu7#V[àü­š‘í•ùT[9\Ó’ª?oçJ©ù…69Ùxß÷¹©ö¼
|ÊOµ°™W##êàÔ²iw®»–uõ5Eíåˆà«ôÅHä¯"‘\PˆÙŽ>ïÖœÖò'¡÷†^Ž#3Sg+ÀéYžt±uBG­>=H'ÞB>”À¾7ƒè)É#)åsU×S‰‡R>µ"\£ô4‹é"ç=D/ÿ-
š¦¼ô©àuCó'´‰ Ë7çPëÑ¿Z½åÛÌ>\Mk
&ʱœÒ0ê*#)ÏAV怩#Bd`^):ܲ¯ü*îÛERk†^ù¦CiÃsõ¦
ší¹Îj¬“*øhf﶑¬†CqíH’ëëIæsŒŠÐ{=ÍW{
:dÓ¸aÐœýjXîæCÃA:æ”CŽÿe5iG£}h7I7ßCüê¬8èqP–t<Ò…©£¸MÄúbª¼EM'ÚJš‘oPýôϽHˆ2GµZ¶¾T
H/Ò¢yb“§ò¦R9ÓC6,n...
I'm using images as a sample at the moment but the finished php should eventually allow to display PDF documents. If it's any help I'm using phpmyadmin and MySQLi.
As the comments suggest, storing the file location in the database is much better than storing the file's data in the database. BUT if you need to store the file contents in the database for some reason, there are two methods. One is using the HTML data: URL and the other is having a PHP file as the middle man.
For the PHP Middle Man method, look at the answer above mine where it sets the header information and then echo's the file contents. The file extension doesn't matter since browsers refer to the content-type header instead of file extensions.
For the Data URL method, which can be placed directly in your code easily check out http://en.wikipedia.org/wiki/Data_URI_scheme
<?php
// Array of valid Mime Types, prevents possible XSS methods.
$valid_mimes = array(
'image/png',
'image/gif',
'image/jpeg'
);
// Obtain Mime Type using finfo
// Finfo allows for strings instead of file path
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime = $finfo->buffer($row['file']);
// Check if mime is in our $valid_mimes array
if(!in_array($mime,$valid_mimes)) {
// Handle Error
echo 'Illegal Mime Type: '.$mime;
die();
}
$b64 = base64_encode($row['file']);
echo '<img src="data:'.$mime.';base64,'.$b64.'" />';
?>
You cant output <img src=\ as an output it will corrupt the image file and
Please use getImage.php as a different file to output images or verify that no output is printed before,after or in mid of image else it will corrupt the image.
if(isset($_GET['id'])){
$sql = "SELECT file FROM table WHERE Res_ID=$referenced_ID";
$result = mysqli_query($dbc, $sql);
$row = mysqli_fetch_assoc($result);
header('Content-type: image/jpg');
echo $row['file'];
}

PHP Echo stops when space in filename occur

I'm trying to show an pdf file stored local in the browser with this code:
<p><a href=<?php
$sql = "select title from tasks where taskPK='".$_SESSION['task']."'";
$res = $db->query($sql);
if (!$res) {
throw new Exception("Database Error [{$db->errno}] {$db->error}");
}
while($row = $res->fetch_assoc()){
$rad= $row['title'];
echo ("files/".$id."/".$rad.".pdf"); }?> > See PDF </a> </p>
This should go into the right folder and get the file and then show it. But my problem is that if the name of the file has an space for example "peter pan.pdf"
Then it won't work. The URL is supposed to be localhost/upload/files/9/Peter%20Pan.pdf
But that doesn't happen. The URL is localhost/upload/filer/9/Peter
It stops when the space hits and the file doesn't show.
But if the filename is connected with a - like this: "Peter-Pan.pdf" it works.
Then the URL becomes localhost/upload/filer/9/Peter-Pan.pdf
And the PDF shows.
Whats the problem? Sorry if it is a bit messy.
$id is the user wich becomes 9 in the URL
The problem should be in here but i can't figuire it out:
echo ("files/".$id."/".$rad.".pdf"); }?> > See PDF </a> </p>
White space is an illegal URL character. Use urlencode to clean $rad.
$rad = urlencode($row['title']);
Regards,
EDIT:
$rad = rawurlencode($row['title']);
This is the reference to rawurlencode

include a PHP result in img src tag [duplicate]

This question already has answers here:
php - insert a variable in an echo string
(10 answers)
Closed 4 years ago.
I am trying to do something I know is probably simple, but I am having the worst time.
I have functioning so far:
1.Script to upload image files to server
2. write the image file names to the database
3. I want to retrieve the image filename from the db and add it to the img src tag
here is my retrieval script
<?php
$hote = 'localhost';
$base = 'dbasename';
$user = 'username';
$pass = '******';
$cnx = mysql_connect ($hote, $user, $pass) or die(mysql_error ());
$ret = mysql_select_db ($base) or die (mysql_error ());
$image_id = mysql_real_escape_string($_GET['ID']);
$sql = "SELECT image FROM image_upload WHERE ID ='$image_id'";
$result = mysql_query($sql);
$image = mysql_result($result, 0);
header('Content-Type: text/html');
echo '<img src="' $image'"/>';
?>
I was trying to pass the Value through image.php?ID=2 but no luck
The PHP script successfully returns the filename, but I cannot for the life of me get it to print it to the html
Any suggestions, please and thank you very much :)
OK, it does return the proper tag, but now it seems as though the script doesnt run to generate the tag.
I have tried two ways:
<div class="slides">
<div class="slide">
<div class="image-holder">
<?php
include ("image.php?ID=2");
?>
</div>
and:
<img src="image.php?ID=2" alt="" />
but neither one will insert the filename...
I need to identify each img src by the primary key, so I was passing it the ID from each image src location
but alas, my PHP ninja skills need to be honed.
Just to clarify: I am uploading images to the server, recording the filenames in a DB and calling that filename in an HTML doc...there are several in each one so I need to pass the ID (i.e. 1,2,3 ) to correspond to the primary key in the table.
But I cant get the script to process the tag first.
If I go to view source, I can click the script and get the proper result...
Thanks again, you guys and girls are very helpful
You're missing the concatenation operator: .:
echo '<img src="' . $image . '"/>';
You can do it as you did but you had the single quotes in twice, (unless you were meaning to use concatenation - which is unnecessary - if you want this see the other answer).
echo "<img src=\"$image\"/>";
Or the longer form with braces if you need to embed inside text.
echo "<img src=\"${image}\"/>";
I'd recommend using heredoc syntax for this if you're doing lots of HTML. This avoids the need to have lots of echo lines.
echo <<< EOF
<div class="example">
<img src="$image" />
</div>
EOF;
Try using this syntax:
echo "<img src=\"$imagePath\" />";
It works with double quotes provided you escape the quotes in the src attribute. Still not sure why the singles don't work.
there are 2 major flaws with your design
There is no image.php?ID=2 file on your disk.
There is absolutely no point in including image.php file. You have to get the name right in the file you are working with. don't you have this row already selected from the database? Why not just print the image name then?
And yes, you are using single quotes where double ones needed.

PHP display image from Database(medium blob)

I currently have a database where i can store images in..
But the PHP page i created to display them... doesnt work.
But when i use the link as scr for a < img> it shows a empty image frame.
if i echo the image directly, i get a lot of strange signs
the way i want to display the images is:
< img src="image.php?image="'.$imageID.'/>
the code i use for displaying the image(image.php) is:
<?php session_start();
if(!isset($_GET['image']))
{
header("HTTP/1.0 404 Not Found");
}
else{
$link = mysql_connect('localhost', '45345345435435345', 'wewfsersdfds');
if (!$link) {
echo "error";
die;
}
$db_selected = mysql_select_db(Tha base, $link);
if (!$db_selected) {
echo "error";
die;
}
$nummer=(int)trim(stripslashes($_GET['image']));
$mynr=$nummer;
$sql="SELECT * FROM Foto WHERE fotonr=$mynr";
$result=mysql_query($sql);
if(!$result)
{
echo "error".mysql_error();
header("HTTP/1.0 404 Not Found");
}
else
{
$foto = mysql_fetch_assoc($result);
header("Content-type: ".$foto['type']);
echo $foto['image'];
}
}
?>
I tried a lot already but it wont work :(
i updated the code to the newest version.
Made mistakes with the sql(selected nothing/never do mysql_real_escape_string of a int)
Now it shows a straight line of characters, instead of an image, thats at least a improvement...
Can someone help me?
Thanx for your time!
Honestly, I know it can be tricky. I think it has to do with how your storing it, not how your outputting it. I have one example of storage from a recent project I can show.
$fp = fopen($image_path, 'r');
$image = fread($fp, filesize($image_path));
$image = addslashes($image);
fclose($fp);
// save $image into DB.
Not sure if you do similar with file_get_contents. How I output is similar to how you are doing it, only I use a ORM and a framework.
I suspect that your problem is in your conversion - perhaps between strings and images, or perhaps between the different image formats.
Have you tried saving the image gotten through image.php, and comparing the binary against the known-good image file? Perhaps once you do that, the answer will be apparent (e.g. wrong length, corrupted header, etc.)
You may want to consider a different database record. Most db's support storage of binary blob data, which you could more simply return. This would be simpler (and take less space in your db!) than using the php functions to stringify and imagecreatefromstring.
Also, I believe that you're attempting to use imagegif, imagejpeg, imaging to perform image format conversion for you. This isn't how I understand them to work, based on my reading at: http://php.net/manual/en/function.imagecreatefromstring.php. Try storing and retrieving the same format to tease out whether this is your problem.
Try looking at Content-type. I think it's case sensitive. Try Content-Type.
http://en.wikipedia.org/wiki/List_of_HTTP_header_fields
$sql = "SELECT * FROM Foto WHERE fotonr=$mynr";
$result = $conn -> query($sql);
while ($row = $result -> fetch_assoc()) {
$img= '<img src="data:image/jpeg;base64,'.base64_encode( $row['image'] ).'" width=350px0px height=300px/>';
}
echo $img;

How to display image from mysql blob in PHP (joomla)

I create a component in my joomla website. the component shows some photos (not big, only 8KB). the photos are stored in mysql blob. i can upload the photos to the joomla database but i cannot display it on the website. whatever i do it only show some encoding character or blank. I tried to create a separate page but but the result is same. Here is what i have done :
mycomp is my joomla component.
admin.mycomp.php
<?php
function showDetail($option)
{
$db = &JFactory::getDBO();
$id = mysql_real_escape_string(JRequest::getVar('id'));
$query = "select id,myphoto from jos_myphotos where id = ".$id;
$db->setQuery($query);
$rows = $db->loadObjectList();
HTML_myphoto::showPhoto($rows,$option);
}
?>
admin.mycomp.html.php
<?php
class HTML_myphoto
{
...
function showPhoto($row,$option)
{
...
header("Content-type: image/jpeg");
echo $row->myphoto; //this will show some encoding character
echo base64_decode($row->myphoto); //this will show blank page
//change echo with print get the same result.
...
}
...
}
I tried to create a separate page like this :
admin.mycomp.html.php
<?php
class HTML_myphoto
{
...
function showPhoto($row,$option)
{
...
?>
<img src="show_image.php?myphoto=<?php echo $row->myphoto;?>" width=200 height=300>
<?php
...
}
...
}
show_image.php
<?php
$myphoto = (isset($_GET['myphoto'])) $_GET['myphoto'] : false;
if($myphoto)
{
header("Content-type: image/jpeg");
echo $myphoto; //this will show some encoding character
echo base64_decode($myphoto); //this will show blank page
//change echo with print get the same result.
}
?>
the result is same.
I think you have 2 options:
Either you make an image tag with its source in a PHP file receiving only a ID parameter and retrieving the photo's string in the DB and echoing it.
Or you echo directly your photo's string in your tag:
<img src="<?php echo base64_decode($myphoto); ?>" />
EDIT
I just checked in an old app where I store the favicons in a DB. You don't need to base64_decode when you display your image inline (my option 2).
So FYI, this image works:
<img alt="" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAABIAAAASABGyWs+AAAACXZwQWcAAAAQAAAAEABcxq3DAAACkElEQVQ4y42TTWyUZRSFn/e+n6W00E4l9ScSCZGODXFLIIZENyZu1ITEGBdE3ejGVQksunDlwoUrE0ICCQuomZAYF4YNNvEPlFpjiJRgKq10HDKdmVJxEOh0vu+9h0UrMSyAk9zVOffczXPRI8hdciVNTZ/X6MjLOnrkK3XTLbk64lEK5FIhaf87HyqznYKy5qsLyuUPL/D1OXzkC8U4IhhViC9o7OAnSkkKksQDVG81GR//iAvTbS7OXIQQ1p0Oc3O/YlCAAAcSQIHIEc43Z8/z6r5xfrsiBp9+ArK4FgprNye//oEMDIJDMBDU6jc4d/YXzpz5kcuzC5SGBvBkoMT257ah5FTn/4Qgpqd+InM3LEDr+j8cO/45pyrnmLk0w0uv7KV/cIDCI4GIhUAgY3h4C9W5Kma9LF//l2xpqc33301xcuJLTp+ehLiJbSNlcpxoEanAolF4okB0lRAiuVOt1cje/+AAly8tcHWhDnEDeAfXKo/FTbg7ZLdwCrDI0PAAK7fvQATkYIbN/l4jWh8pAb4BrJ/abI32301MXULKoIhE9bKxt8RKJ4D1gXpIitj+d19j6PGN7CiXQavgHYir3G5fY+tT/Wx/cgulnh6su0JYvUPodiHvAGJz32YoJC222qo1lvTH1b906NBngq06cPBjFZKkXIuNmhZbN3RlvqUTlUnt2fumsGc0NvapkJLcpeRrzF+r31R5dLd2PP+i6s3if//gcndJUqPRUKVSUbPZFCnlkpJcSWmd+dffeE/BntWJk9/eW7q/RJJSSjIzQxKBhIUcgN17dhFCxsREheXlZSStZUIghEBRFACYGRlwz3Q5FuDtt/Yx/fMFSqVB8jwnrPP/Xy7LMtwdM+Mu+2gfA7SP0igAAAAASUVORK5CYII=" style="margin-right: 5px; vertical-align: middle;" class="bbns_itemDragger">
And it is stored in my DB like this (base64 encoded):
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAABIAAAASABGyWs+AAAACXZwQWcAAAAQAAAAEABcxq3DAAACkElEQVQ4y42TTWyUZRSFn/e+n6W00E4l9ScSCZGODXFLIIZENyZu1ITEGBdE3ejGVQksunDlwoUrE0ICCQuomZAYF4YNNvEPlFpjiJRgKq10HDKdmVJxEOh0vu+9h0UrMSyAk9zVOffczXPRI8hdciVNTZ/X6MjLOnrkK3XTLbk64lEK5FIhaf87HyqznYKy5qsLyuUPL/D1OXzkC8U4IhhViC9o7OAnSkkKksQDVG81GR//iAvTbS7OXIQQ1p0Oc3O/YlCAAAcSQIHIEc43Z8/z6r5xfrsiBp9+ArK4FgprNye//oEMDIJDMBDU6jc4d/YXzpz5kcuzC5SGBvBkoMT257ah5FTn/4Qgpqd+InM3LEDr+j8cO/45pyrnmLk0w0uv7KV/cIDCI4GIhUAgY3h4C9W5Kma9LF//l2xpqc33301xcuJLTp+ehLiJbSNlcpxoEanAolF4okB0lRAiuVOt1cje/+AAly8tcHWhDnEDeAfXKo/FTbg7ZLdwCrDI0PAAK7fvQATkYIbN/l4jWh8pAb4BrJ/abI32301MXULKoIhE9bKxt8RKJ4D1gXpIitj+d19j6PGN7CiXQavgHYir3G5fY+tT/Wx/cgulnh6su0JYvUPodiHvAGJz32YoJC222qo1lvTH1b906NBngq06cPBjFZKkXIuNmhZbN3RlvqUTlUnt2fumsGc0NvapkJLcpeRrzF+r31R5dLd2PP+i6s3if//gcndJUqPRUKVSUbPZFCnlkpJcSWmd+dffeE/BntWJk9/eW7q/RJJSSjIzQxKBhIUcgN17dhFCxsREheXlZSStZUIghEBRFACYGRlwz3Q5FuDtt/Yx/fMFSqVB8jwnrPP/Xy7LMtwdM+Mu+2gfA7SP0igAAAAASUVORK5CYII=
I'm sorry, did you skip some lines from show_image.php?!
Cause $myphoto is just the id of the photo. You can't base64_decode an ID.

Categories