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Ë!üioe8
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'];
}
Related
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.'>";
I have images stored in mssql database . I want to retrieve the data via php and create image file . I have tried numerous possibilities but unable to find any correct solution
Image i have in following format stored in database
0xFFD8FFE000104A46494600010200000100010000FFDB00840001010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010
I have tried
$row = mssql_fetch_assoc($result);
$db_img = $row['imgdata'];
$db_img = pack("H" . strlen($db_img), $db_img);
header("Content-Type: image/jpeg");
echo $db_img;
displays black image
Also i have tried
file_put_contents( 'test_image.jpg', $binary_data);
Not Working ....
Also tried ...
imagecreatefromstring("0xFFD8FFE000104A46494600010200000100010000FFDB00840001010101010101010101010101010101010101010101010101010101010101010101010101.........");
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
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;
I've stored my Images into (Medium) BLOB fields and want to retrieve them embedded within my PHP-generated web pages.
When I test retrieving the stored images using
header('Content-type: ' . $image['mime_type']);
echo $image['file_data'];
everything looks just fine.
However, I have not yet found a way to retrieve the image(s) cleanly into the middle of my documents. For example, using
$image = $row['file_data'];
echo '<img src="data:image/jpeg;base64,'.$image['file_data'].'" alt="photo"><br>';
...or...
$im = imageCreateFromString($image);
I just wind up with a bunch of hexadecimal garbage on screen.
I intitially stored the Images using:
ob_start();
imagejpeg($resizedImage, null, 100);
$content = ob_get_contents();
ob_end_clean();
$sql = sprintf(
"insert into images (filename, mime_type, file_size, file_data, event_id)
values ('%s', '%s', %d, '%s',%d)",
mysql_real_escape_string($fileName),
mysql_real_escape_string($mimeType),
$imageSize,
mysql_real_escape_string($content),
$eventID
);
$result = $cn->query($sql);
Does anyone PLEASE have a working code snippet to successfully display the stored .jpg mid-file in the PHP output?
echo '<img src="data:image/jpeg;base64,'.base64_encode($image['file_data']).'" alt="photo"><br>';
However, remember that old IE versions do not support this kind of inline images! Besides that, the browser cannot cache such an image except together with its containing HTML page.
You should create some sort of "image server". You're already close to that.
For example, create something like image.php that will get a image name and will generate it on the fly.
So, for example, say you want to get somePic.jpg image. You can get it through:
image.php?name=somePic.jpg
<?php
header('Content-type: ' . $image['mime_type']);
echo $image['file_data'];
?>
Your tag:
<img src='image.php?name=somePic.jpg' />
Or more general:
echo "<img src='image.php?name={$image['filename']}' />"
Why not just call your test page image.php, then have it called from the browser on the rendered page:
<img src="image.php?imageid=123" alt="photo" />