okay so it is appearing to me my header() isn't doing anything. i tried moving it to the very top of the file instead nothing changed unless I put it in its own but then the rest of the file doesn't run but it does send the header.
EDIT: I updated my code with your suggestions, but it still isn't working correctly. Below is an image of the network tab when I inspect the page. The big thing I notice is the calls are being made but its fetching the same about of data for every image and its a very tiny amount of data.
edit: I am getting and Invalid URL Error when I inspect in chrome unless I remove data:image/png;base64,
Referrer Policy: strict-origin-when-cross-origin
I can't seem to get this working correctly. The png image should be pulling from the database and then displaying in the HTML. (and yes I know this isn't SQL injection safe) I assume there is some issue with it being called from the loop, but I am unsure. Or that it can't find the getImage.php to use it this way do i need to import it or something earlier in the code? It does correctly pull in the item_id. The result just gives me a broken image box. I know my getImage.php is outputting the correctly formatted image, because I have taken the output directly from there and inserted in place of the call for it and the image has show up. So it tells me this line below is my issue
echo ('<td><img src='"getImage.php?image_id="' . $row["item_id"].'"></td><td>');
if I edit as follows it works fine (but obviously it give me the same image for every entry) DBS is the decoded byte string that getImage.php outputs
echo ('<td><img src="data:image/png;base64,DBS"></td><td>');
PHP for the Front Facing page (blackmarket.php:
$sql="SELECT * FROM `item` WHERE 1";
$result = $link->query($sql);
echo("<table>");
if ($result->num_rows > 0) {
// output data of each row
echo("<tr>");
while($row = $result->fetch_assoc()) {
$newrow=0;
echo("<td>");
echo ('<img src="getImage.php?image_id='.$row['item_id'].'" />');
getImage.php:
<?php
require_once "connect.php";
if(isset($_GET['item_id'])) {
$sql = "SELECT item_img FROM item WHERE item_id=" . $_GET['item_id'];
$result = mysqli_query($link, $sql) or die("<b>Error:</b> I can't find the image <br/>" . mysqli_error($link));
$row = mysqli_fetch_array($result);
header("Content-type: image/png");
header("Content-Length: " . strlen($row["item_img"]));
echo $row["item_img"];
}
mysqli_close($link);
Just specify
echo "<td><img src=\"getImage.php?image_id={$row['item_id']}\"></td>";
The browser is responsible for assembling the page, and makes a separate call to the getImage.php script and reads the image data that you are returning.
Return the binary image data directly, along with the size. This might also be part of the problem.
<?php
require_once "connect.php";
if(isset($_GET['item_id'])) {
$sql = "SELECT item_img FROM item WHERE item_id=" . $_GET['item_id'];
$result = mysqli_query($link, $sql) or die("<b>Error:</b> I can't find the image <br/>" . mysqli_error($link));
$row = mysqli_fetch_array($result);
header("Content-type: image/png");
header("Content-Length: " . strlen($row['item_img']));
echo $row['item_img'];
}
mysqli_close($link);
Omit the closing php end tag ?> from this script. PHP best practices is to omit it for all scripts but it is especially important in a script like this that returns binary data, as a bit of whitespace or a UTF-8 BOM character can corrupt your output and is often hard to debug.
You are confusing two things:
data: URIs allow you to embed an image directly in the source code of an HTML page, so that the browser can render them immediately without another call to the server. They use base64 to make the data consist only of text, because you can't put non-text characters in the middle of your HTML source code
Normal https: URLs tell the browser to make a request to the server, which returns the image data, with no extra encoding needed. Most commonly, the web server will load the image straight from disk, but the browser doesn't know about that, so you can just as validly have a PHP script which returns the same data, based on whatever logic you want.
In your code, you've mixed the two: you've prefixed a normal URL with data:, so the browser is expecting the data right there in the source code, and never makes a call to getImage.php.
What you need to do instead is make sure that in your getImage.php you
echo out just the image data - no whitespace or debug output mixed in
not base64 encoded (if it's stored in the database that way, decode it before sending to the browser)
tell the browser it's an image with an appropriate Content-Type header, e.g. header('Content-Type: image/png'); - again, no mention of base64 encoding or anything else, you're serving an image just as if it was a file on your server
You shouldn't need to set the Content-Length header manually, the server will sort that out just like it would if you were outputting HTML
You can then load that image URL directly in the browser and it should display, no need to even look at your HTML until that part is working right.
Well I finally figured out what was going wrong. In my connect.php I had some white space and that white space was being called before my header so my header wouldn't work
Related
I am trying to display an image from a MySQL database on a webpage using PHP. I am aware that this is not the most efficient method, but still I would like to see how it is done....
To insert the image into the database I am using this code:
//Get File
File file = new File("C:\\Users\\blah\\blah\\blah\\WebcamImage\\" + name);
FileInputStream fileStream = new FileInputStream(file);
//Prepared Statement
pStmt = connection.prepareStatement("INSERT INTO table (webcamPic1) values (?)");
pStmt.setBinaryStream(1, fileStream, (int) file.length());
pStmt.executeUpdate();
To display the image on the website, I currently have this PHP code:
$result = mysqli_query($con,"SELECT * FROM table");
header('Content-Type: image/jpeg;');
echo "<table border='1' title='WEBCAM'>
<caption>WEBCAM</caption>
<tr>
<th>WEBCAM 1</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['webcamPic1'] .
"</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
On the webpage the file is displayed as a mess of symbols, like this:
ÿØÿàJFIFÿÛC $.' ",#(7),01444'9=82<.342ÿÛC
2!!22222222222222222222222222222222222222222222222222ÿÀz£!ÿÄÿÄC!1AQa"q2‘¡±Á#Bá3RÑðbrñ$4CSc¢s’“ÂÒÿÄÿÄ(!1AQa"2q‘¡ðBÿÚ?ûö„ã=–Ù0Xa˜#•7BÀÙ”BTà÷#DÂ.€Å¬´
7……Óc¨L1„¡£ì·2€Ä#?tû7A‘öTl¢ƒÂeEUn#BØ#r°#Â%TCŠ(€±#,±##„” RBÔB‘Â
}’¢µ!•HHá›'±'')DÝ”%#Í7 Ì((hTm¥)U æð¦[쨑6HE¾Pl%sA"æ[ÔûJ¨‹©OHh°7s
Iáp€Ñ¨":µþ¦³Ó÷5¨Ò¼Ñ©ÿí÷]'âäŸöG'àèVqw«ý&Çì¹êøY&'¡Y²ñ¹Wg)±Âï
‡·òYCÿ_¥4÷NÜ.m˜,ƒ„¨g²3öEdÃBžrº¿^·º á•Flˆ!5Õ„NxZ0ˆP…¯>ꨢ
¡Aº£eFYD-!E•)‚ÓÙ›!•Xª2^Pct§•B‘ tŽmÐ) e¨$B‹ÇQ¥•V¹Af:EøU”£
Kð®¡OµÒk 8)œ•r›lØýղТêRˆçÔm¡HÔp0,¹qàé[¢h~³kêäRË)vîîë·ãžØåßD«YpÕ«+ÑÆ9×
gƒž0ºü;\ÚÕ›Pá$C“Ð÷Sòðùqþ‰ÇŸÇ“Ó>Âg=Ö^z>UëL”Àñu0ÇdgªŠåü‘Y8„%0##dÃ(0ˆˆ¼
+| ל¦‚xEY„£÷TˆƒÙÁ[¿T-•” ìUYˆ?+ <#‰ESŽot‹€è(*Â4 E•jRBƒÂ ¸YEÌIÌ ¨°((×BèkïÑA#dvYX€”‰TIÀ©Pm·”ûP
Obviously I am doing something very wrong. What is the correct way to display the true image?
Thank you.
You are mixing two different contents in single HTTP response - it does not work that way and you cannot send HTML and images combined as HTTP does not support multiplexing (SPDY does for example). So this is wrong in the way you do it as browser does NOT expect this and is unable to separate one from the other considering all data it receives in this response as HTML document, hence garbage you seeing as it expects text and handles it all as such. To do this right way, you should have separate PHP script that will return image content, but the request for it should come from browser. So you should just return URL to your image script in SRC for image:
<img src="image.php">
and output image from image.php if so.
Also your code current code makes no sense from other reason too:
header('Content-Type: image/jpeg;');
echo "<table border='1' title='WEBCAM'>
since HTML is NOT image/jpeg type.
PS: storing images in database is considered very bad idea. Store images on disk and keep references to it in your db records only.
There is way to this try something like this:
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot" />
data uri notation should do the job.
last part of the uri i base64 encoded image.
So You just should get Your image data from database encode it with base64_encode and then return it to the browser
For more details check this:
http://en.wikipedia.org/wiki/Data_URI_scheme
I have uploaded an Image in my database. The datatype is BLOB. Now I want to view this image in my browser. I have written the following code but its not generating the image. Kindly check it.
Thanks
<?php
include 'connect.php';
//$id= $_GET['product_id'];
$query_images = "SELECT image FROM product_images WHERE product_id=121";
if (!$query_images_result = mysql_query($query_images))
{
echo mysql_error();
}
else
{
$fetch_images = mysql_fetch_array($query_images_result);
$print_images = $fetch_images['image'];
header('Content-type:image/jpeg');
echo $print_images;
}
?>
File 2
<body>
<img src='single_product_image_show.php' alt="image" />
</body>
maybe something like this? You might wanna use base64 encoding to build in the image
FYI: NOT TESTED.
$sql = "SELECT `image` FROM `product_images` WHERE `product_id`=121 LIMIT 1";
$query_images_result = mysql_query($sql);
if (!$query_images_result)
{
echo mysql_error();
}
else
{
list($print_images) = mysql_fetch_array($query_images_result);
$base64source = "data:image/jpeg;base64," . base64_encode($print_images);
echo '<img src="'.$base64source.'" alt="" />';
}
There are multiple possible reasons why this could happen. First try your script directly without "header('Content-type:image/jpeg');" so you can see what it actually returns. Like http://[youhostname]/single_product_image_show.php I assume you will see some errors.
Some best practices to serve images from php:
If you can remove the end php tag (?>). You don't actually need it and you can avoid issues when you have whitespace character after the close tag which will be written to the response and so results as a corrupt image.
You should specify the Content-Length header as well. It's not mandatory but the browser
will know how big the file it has to download.
Specify some cache control headers (https://en.wikipedia.org/wiki/List_of_HTTP_header_fields) so browsers can cache your image so it won't result a full page load and mysql query every time the image appears on the site.
You can store ETag and/or Last-modified in the database which you can retrieve and put in the headers.
The following problem I can't really wrap my mind around, so really if you guys can't be bothered to supply the entire code some tips leading in the right direction would be great!
So, I have a script where users can upload images to a server. PHP takes care of validating the file and saving it using a new filename in another folder, neither known by the client. Now, the client should be able to see the uploaded image, in html simply:
style="background-image:url('testimagegif.gif');
But preferably the client should not be able to see the path nor the file name of the image saved on the server. I know about using header('Content-type: ... for forcing the client browser to download files, but I do not see how this, nor any similar solution could be applied to this case. Same goes for readfile. If I use it the browser simply downloads the image, not placing it in the html.
You should probably be moving the files into a publicly readable folder on your webserver if you want to serve them.
Otherwise, you'll need something like readfile()
There are two options for this, you could use the data protocol, which would embed the whole image into the URL of the background ( this isn't recommended if the image is bigger than a few kb. ) or you can use a script to present the image by encoding or recording a unique key for the image, eg bg.php?id=4323-34442-3432-4532 which checks a db for the id to retrieve the file path then echoes the content with the right content type.
Some examples;
based on the Data URI wikipedia page
Data URI Method
Assuming a function like this;
function data_uri($fileID) {
$fRecord = mysql_fetch_array(
mysql_select("SELECT filePath, mimeType from fileTable WHERE fileID = " $fileID . ";")
);
$contents = file_get_contents($fRecord['filePath']);
$base64 = base64_encode($contents);
return "data:$fRecord['mimeType'];base64,$base64";
}
Then in your html/php page you'd have the following snippet
style="background-image:url('<?php echo data_uri($fileID);?>'
PHP Image Dump
Assuming a function like this;
// Given a filename and a mimetype; dump the contents to the screen
function showDocumentContent($fileID){
$fRecord = mysql_fetch_array(
mysql_select("SELECT filePath, mimeType from fileTable WHERE fileID = " $fileID . ";")
);
header( 'Content-Encoding: none', true );
header( 'Content-Type: ' . $fRecord['mimeType'], true );
echo readfile( $fRecord['filePath'] );
}
Then in your html page you'd have this;
style="background-image:url('image.php?fileID=123')
In the first case, images larger than a few KB will result in equally large HTML pages, and may not be supported in browsers consistently. In the second case, you'd effectively have created a php script that is pretending to be an image. In both cases, the real path to the binary files on your server is abstracted away by storing a mapping in a database.
If you store the paths to the files somewhere like a database or a file, you can use readfile() to output the file once you retrieve the path.
Combine that with the content-type header, and set the background-image URL to the PHP script with the correct query string like so:
style="background-image:url('script.php?img=30382');"
You must expose some path to the client, because their browser has to access the file. You can use your webserver config to serve at an indirected location, or serve the image with PHP and have the real path in a call to readfile()
I need to send a GET request to my page pic.php, and I want to get a real picture in return.
For now I implemented this idea like this:
<?php
if ((isset($_GET['pic']))&&(isset($_GET['key']))){
$pic = $_GET['pic'];
$pic=stripslashes($pic);
header('Location: /content/'.$pic);
}
?>
But it's not really what I want - it redirects to image directly. What I want is to keep the same URL, but get a needed file depending on what values were submitted.
What is the best way to do that?
thx.
This example code snippet should do what you ask. I've also included code to only strip slashes if magic quotes is enabled on the server. This will make your code more portable, and compatible with future versions of PHP. I also added use of getimagesize() to detect the MIME type so that you output the proper headers for the image, and do not have to assume it is of a specific type.
<?php
if(isset($_GET['pic']))
{
//Only strip slashes if magic quotes is enabled.
$pic = (get_magic_quotes_gpc()) ? stripslashes($_GET['pic']) : $_GET['pic'];
//Change this to the correct path for your file on the server.
$pic = '/your/path/to/real/image/location/'.$pic;
//This will get info about the image, including the mime type.
//The function is called getimagesize(), which is misleading
//because it does much more than that.
$size = getimagesize($pic);
//Now that you know the mime type, include it in the header.
header('Content-type: '.$size['mime']);
//Read the image and send it directly to the output.
readfile($pic);
}
?>
I can see you doing this in two ways:
1) Return the URL to the image, and print out an image tag:
print '<img src=' . $img_url . ' />';
2) Alternatively, you could just pull the data for the image, and display it. For instance, set the header appropriately, and then just print the image data.
header("content-type: image/png");
print $img_data;
This assumes that you have the image data stored in a string $img_data. This method will also prevent you from displaying other things on the page. You can only display the image.
You can load the image, send the image headers, and display the image as such:
header('Content-Type: image/jpeg');
readfile('/path/to/content/pic.jpg');
Obviously the headers would depend on the filetype, but that's easy to make dynamic.
Not sure if I understand what you're after, but guessing that you want to load the picture in an img tag?
If I'm right you just do:
<img src=http://www.domain.com/pic.php?"<?php echo image here ?>" />
Basically you just make the source of the image the webpage you get directed to where the image is.
I have a specific problem, and cant get over it.
For my latest project I need a simple PHP script that display an image according to its ID sent through URL. Here's the code:
header("Content-type: image/jpeg");
$img = $_GET["img"];
echo file_get_contents("http://www.somesite.hr/images/$img");
The problem is that the image doesn't show although the browser recognizes it (i can see it in the page title), instead I get the image URL printed out.
It doesn't work neither on a server with remote access allowed nor with one without.
Also, nothing is printed or echoed before the header.
I wonder if it is a content type error, or something else.
Thanks in advance.
Possibly the image doesn't fit into memory. Or your PHP installation doesn't have permissions to make external HTTP calls. Anyway, I suggest you never use echo file_get_contents(), use readfile instead.
Also you should never use raw strings from $_GET or $_POST for file operations. Always strip null-bytes, slashes and double dots from user-provided filenames, or better yet, allow only alphanumeric characters.
I was doing something like this recently, but found this a slow method (I was doing 15+ on a page). This is slow because first your server has to download the image, and then send it to the client. This means for every image it is downloaded twice.
I came up with an alternative - redirection. This allowed the client machines to directly access the other site while hiding the real url in the HTML source code.
$r - is processed above the script, and validated to make sure it is ok.
$webFile = 'http://www.somesite.com/'.$r['type'].'/'.$r['productid'].'.jpg';
header('Location: '.$webFile);
exit();
Granted if someone put my image url in the address bar, it would redirect and the user would see the real url, but it made my page faster and I wasn't too worried about that.
You'll want to ensure that your script is not outputting any white-space. Check before and after the opening/closing PHP tags.
If that checks out, you'll want to ensure that allow_url_fopen is set to On in php.ini
try embedding your php file that retrieves the image as <img> in your html
getImage.php
header("Content-type: image/jpeg");
$img = $_GET["img"];
echo file_get_contents("http://www.somesite.hr/images/$img");
in your html file
<img src="getImage.php?img=IMAGEID">
Probably you get some errors and the image is not displayed. Try to turn off the errors like this first:
ini_set('error_reporting', E_ALL);
ini_set('display_errors', 'Off');
Check that the variable exists in the query string, and use a regular expression to make sure that it doesn't contain anything other than alphanumeric characters or a period. Then use readfile() to stream the output to the browser.
// make sure the variable exists
if (isset($_GET['image'])) {
$image = $_GET['image'];
// make sure it contains only letters, numbers, the underscore, and a period
if (preg_match('/^[\w.]+$/', $image)) {
$file = "http://www.example.com/images/$image";
// send the correct header
header('Content-type: image/jpeg');
// stream the output
readfile($file);
}
}