PHP display image from Database(medium blob) - php

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;

Related

php - set photo to image by path [duplicate]

This question already has answers here:
Output an Image in PHP
(12 answers)
Closed 4 years ago.
Well, my page contains an img like this:
<img id=".."class=".." src="setPhoto/second_photo.php">
Now, as you can see in src I have put a .php file:
<?php
$id = $_SESSION['u_id'];
$sql = "SELECT * FROM users WHERE id=$id";
$result = mysql_query("$sql");
if ($row = mysqli_fetch_assoc($result)) {
mysql_close($link);
header("Content-type: image/jpeg");
echo $row['profile_front_photo'];
} else {
// no result from database
mysql_close($link);
header("Content-type: image/jpeg");
echo '../../../_images/default.jpg'; //Here is the promblem
}
?>
This code with the path, is not working. I want to set a photo to img by using a path.
Is it possible?
The browser asked for an image. Instead of getting an image back, it got back a string "../../../_images/default.jpg".
Instead, you want to open that file and pass its contents through. You also need to set the correct MIME type in the response.
You should be able to find simple tutorials for this online, or take a look at e.g. https://secure.php.net/manual/en/function.fpassthru.php
You can try this:
dirname(__FILE__)
it will get the root folder your project and then you specified your path like this
dirname(__FILE__). '/imagefoldername/_images/default.jpg';
Make it
$path='../../../_images/default.jpg';
echo "<img src='.$path.'>";

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

PDO to retrieve and display images without creating files

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

How to display image depending of result in MySQL query, using PHP

I was wondering for some time, and searching the nets, for an efficient way of displaying an image dynamically using PHP, depending on the result of a query. Per example, there is a field called "devicetype" in my asset table, and I would like to display a different icon depending on the type of device.
Anyone could point me in the right direction? I've been reading around and many articles recommend against inserting images into the DB.
Thanks!
You don't need to insert the images into the DB. Just check the value of the column in your table and then use the appropriate image source based on it. Something like this:
while( $row = mysql_fetch_assoc($result) ) {
$src = '';
switch( $row['devicetype'] ) {
case 'device1':
$src = 'img_for_device.jpg';
break;
case 'device2':
$src = 'img_for_device2.jpg';
break;
default:
$src = 'default.jpg';
}
?><img src="<?php echo $src; ?>" /><?php
}
I would store image in your website folder i.e. "website/deviceimg/*". Then, depending on your sql statement, I would load corresponding image by its name. For example, you might use devicetypes as image names. Loading image is fairly easy:
"< img src=' + devicetype + '.jpg' />"
I'm not sure I fully understand your question but can't you upload all the images you're going to use on your server? I think that's better than storing the actual images in your DB.
So your code will be something like this:
if (results[devicetype] == "A") {
echo '<img src="images/A.png" />'
else if (results[devicetype] == "B") {
echo '<img src="images/B.png" />'
You can insert a link to the image file in the DB.

Categories