PHP: Obtaining image from other PHP script - php

I'm having kind of controller http://samplesite.com/application/getimage written in php. It is a simple script that responds to GET with some parameters. According to these parameters I find an image in database (image is stored there as a BLOB) and I return it as follows:
header("Content-type: image/jpeg");
echo $image;
$image is a BLOB of image obtained from database.
When I open this URL http://samplesite.com/application/getimage/?id=200 my web browser displays an image.
Now I want to display this image inside a table in another php script. I want to perform it like
echo "<img src="http://mysite.com/application/getimage/?id=200" ...some params here... />";
but
this approach does not work. It displays no image or makes other problems.
What approach should I choose to make this work? I'm new to php normally work with Java EE. Thanks very much.
EDIT:
Of course there should be inside the echo \" and not only ". But this approach that I wrote here works fine. Problem was in syntax, I had one extra ).

Passing a PHP file AS an image (not recommended)
Your issue is that you haven't escaped speech marks, replace:
echo "<img src="http://mysite.com/application/getimage/?id=200" ...some params here... />";
With:
echo "<img src='http://mysite.com/application/getimage/?id=200' ...some params here... />";
or:
echo "<img src=\"http://mysite.com/application/getimage/?id=200\" ...some params here... />";
However, there is a far better way to do this:
Using image BLOBs properly
You're on the right track -- you can use an image BLOB instead of a file to put an image inline, but there's a little more work to it. First, you need to base64_encode the blob before you pass it. You should omit the header as you're passing text, not an image:
echo base64_encode($image);
Next, you need to set up the image tag like this, declaring that you are using data, the mime type and finally including the output of your getimage script as declared by RFC2557:
<img src="data:image/jpeg;base64,<?php include('http://mysite.com/application/getimage/?id=200'); ?>"/>
That should fix the issue.

Related

display image from HTML page using PHP without calling PHP script or using PHP echo to hide image path

I want to display images, from files, in an HTML webpage, using PHP to hide the location of the files, using PHP header/readfile, and avoiding any PHP that would reveal the file location (such as echo).
So far I've only been able to get this working by calling a PHP scrpit from the HTML, but would prefer to do so without calling a script, so a viewer has no sight of the PHP script file. I do not want to use a PHP file rather than HTML file (so a viewer couldn't type the URL of the PHP script in themselves).
image.php:
<?php
header('Content-Type:image/jpeg');
readfile('../image.jpg');
?>
image.html:
<html>
...
<img src="image.php"/>
In the HTML file I would like to do the equivalent but in-line:
<html>
...
<img src="<?php header('Content-Type:image/jpeg');readfile('../image.jpg');?>"/>
Or:
<html>
...
<?php
echo '<img src="';
header('Content-Type:image/jpeg');
readfile('../image.jpg');
echo '"/>';
?>
I suspect my lack of understanding of how HTML and PHP work together is letting me down here.
I would like to do the equivalent but in-line:
You cannot. You must have separate request. You could optionally inline the image as base64 but that bad idea anyway.
Also this code looks like pointless - you just exposing existing file w/o any benefit of doing that yourself BUT with the penalty of killing all the caching and other features browsers could do. Unless you know how to do that properly (this is not that trivial), you are complicating simple thing instead of simplifying complicated.
What you want can not be done as you're trying. You can echo the contents via the base64 aproach. but that would make your html grow in size very rapidly, which isnt good for performance.
There is a way you can get it to work though. It's a bit trickier, but you can use your .htaccess file for this. Normally you often use it to rewrite some url to redirect the url to the index.php. You can also use it to create an image url:
RewriteEngine On
RewriteRule ^/special-images/(.*)\.jpg$ /php-file-directory/image.php?image-name=$1 [L]
If you now do <img src="/special-images/bob.jpg" /> it will internally open-image.php with $_GET['image-name'] being bob.
*Cant test the htaccess right now, but you get the gist of it.
try coverting it to a data url
https://stackoverflow.com/a/13758760/11485791
example:
<img src="<?
php path = '../image.jpg';
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
echo $base64;
?>"/>
but then the returned html would be huge

Store image in variable, echo later

Let's say I have a user enter the URL of an image.
After URL validation, etc. I want to get the image and store it in a PHP variable. Not the image path, but the actual image itself.
I am adding this image-holding variable in between other strings, so I cannot change use header() before echoing the image. Is it possible to use <img> HTML tags? I really don't want to copy the images to my own server...
How do I:
Store the image in a variable such that,
Echo the image from the variable without changing headers.
Edit:
I said above that I am putting this image inside another variable, e.g.:
$str = "blah blah" . $var_holding_img . "more text";
Is it possible to insert something in the string above that will be replaced with the images? Can parse the variable $str later to replace some random text like "abg30j-as" with the image...
I found an answer to my own question:
First, I created another PHP file, called img.php:
<?php
$url = $_GET['imgurl'];
/*
Conduct image verification, etc.
*/
$img_ext = get_ext($url); //Create function "get_ext()" that gets file extension
header('Content-type: image/' . $img_ext);
echo file_get_contents($url);
?>
Then, in the original PHP file, I used this PHP code:
<?php
$var_holding_img = '<img src="img.php?imgurl=http://example.com/image.png"/>';
$string = "This is an image:<br \>" . $var_holding_img . "<br \>displayed dynamically with PHP.";
echo $string;
?>
This way, the PHP file "img.php" can use the proper headers and the image can be inserted as HTML into any other PHP variable.
How do I:
Store the image in a variable such that,
Echo the image from the variable without changing headers.
You can do this in two ways.
In way one, you serialize the image in a string, and save the string in the session. Which is exactly the same as saving it server side, except that now the session GC should take care of clearing it for you. Then the IMG SRC you use will redirect to a script that takes the image and outputs it as image with proper MIME type.
In way two, if the image is small enough, you can encode it as BASE64 and output it into a specially crafted IMG tag:
http://www.sweeting.org/mark/blog/2005/07/12/base64-encoded-images-embedded-in-html
This saves you some time in connection, also. Of course the image must be reasonably small.
You can't save the actual image in a variable. Either you save the URL or copy the image (what you obvious don't want) to your server and save the path to the image
See answer 1, you can't echo the image itself, only link it
Edit: Okay obviously you can save images directly to a variable, but I don't recommend you to do this.
No, that isn't possible. If you want to serve something, it has to exist on the server.

PHP - send GET request and get picture in return

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.

In PHP, how I show various images from a BLOB field in the database with the HTML content?

I stored it images in the database using an BLOB field (I'm using SQLite). Now I want to recover this image to a HTML page and show the images there.
I can retrieve the binary data from the image from the database, but what I can do to transform this data in an image and show in the page? Currently I want to show the images inside a field in a table.
You could abuse the data: protocol, but trust me, you don't want that if you can avoid it. Normally, you create a separate php-script that serves images, so in script 1:
<img src="/myimagescript.php?id=1234">
In myimagescript.php:
//get the data from the database somehow (mysql query et al.)
//let's assuma the data is in $data
header('Content-Type: image/jpeg');//alter for png/gif/etc.
echo $data;
#uscere90 is right, but an example might help (example of a PNG image):
<?php
header("Content-type: image/png");
echo $image_data;
?>
Typically this is done by creating a wrapper script or function that retrieves the BLOB and delivers it with the appropriate content headers to be used as an <img src=''>
Doing it this way also gives you the benefit of being able to deliver or not deliver the image based on other authentication factors determined by your PHP. If, for example, a user doesn't have permission to see an image, you can instead show some default or blocking image in its place.
// File getimg.php
// Retrieve the image blob specified by $_GET['imgid'] from the database
// Assuming your blob is now in the variable $image...
header("Content-type: image/jpeg");
// Just echo out the image data
echo $image;
exit();
Now in your html:
<img src='getimg.php?imgid=12345' alt='this is your img from the database' />
You can create a simple image.php page that queries your database, then prints out a content-type relevant to the image and vomits the binary data to screen. So, in your table, you'd have <img src=image.php?id=something />, and then you'd use that id in your image.php page to do your database lookup, retrieve the binary data, and print it to screen after printing the content-type header.
image.php:
<?php
header('Content-type: image/jpeg');
//DO SQL NINJA STUFF HERE
echo mysql_result($result,0,"file_content");
?>
There are two options I would say:
You create a script that returns the image data. The <img src="-field then calls that script.
You offer the data of the images directly via a data url.
Both have it's pros and cons. For the first solution you must create a new script for the images. The second method will bloat your page if the images are large.
As there are examples for the image script method already, here is some code fragment for data URIs:
<?php
function data_uri($content, $mime)
{
$base64 = base64_encode($content);
return ('data:' . $mime . ';base64,' . $base64);
}
?>
<img src="<?php echo data_uri($content,'image/png'); ?>" />
You need to set the mime-type according to your image, image/png for PNG images, image/jpeg for JPG files etc., see here for a list.

How is $_GET set in this image-resize code?

I am working with a script for resizing images. I seem to be getting an error:
Error: no image was specified
Probably because of this code in the script(image.php):
if (!isset($_GET['image']))
{
header('HTTP/1.1 400 Bad Request');
echo 'Error: no image was specified';
exit();
}
Here is what I'm doing(profile.php):
$your_image = $row['Image'];
$path_to_image = $row['PortraitPath'];
$width = 100;
$height = 100;
echo "<img src=\'/image.php/{$your_image}?width={$width}&height={$height}&cropratio=1:1&image={$path_to_img}\' alt=\'Alt text goes here.\' />";
Therefore, I am reading $your_image and $path_to_image from a MySQL table, and then putting it in the img source. As mentioned above, obviously, image is not set, that is why I am getting that first error. What I don't get is, how will the image actually even be set with my img src code? Aren't I simply displaying the actual image? Then how will image even be set if a picture is simply being displayed? Thank you.
If you want to source a php file instead an image, you need to tell your php file that the output will be an image.
You can do this using the php header() function, like this:
header('Content-type: image/jpeg');
Here is some reference: php header function
About the address you are point to, isn't a bit weird? You have a slash right after the .php, which suggest that you are trying to access some folder... Did you tested this url to see if a real image are being outputted on the screen?
Hope this can help you =)
The URl for the image contains ?foo=bar&this=that&image=path. These variables will be passed to the image.php script in the $_GET array.
As a word of warning, in your profile.php's code I saw this fragment:
image={$path_to_img}
Depending on how you deal with the value of $_GET['image'] this may result in a RFI vulnerability. The user could forge a GET request to image.php with their own "image" path.
A couple things that I noticed, I'm not sure how much of the code you modified before posting it here...
1a) Don't escape the single quotes if you are using double quotes to encompass it.
OR
1b) Change the escaped single quotes to escaped double quotes.
2) In the URL you are using $path_to_img but the variable you have defined is $path_to_image. Make them consistent.

Categories