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

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.

Related

Read multiple image files using php readfile

I am trying to read multiple image files from a folder (.htaccess protected) and display in a HTML page using php readfile().
The problem is I can see only the first image is read and the next is not shown in the browser. The code is as below
<?php
$image1 = 'files/com_download\256\50\www\res\icon\android\icon-36-ldpi.png';
$image2 = 'files/com_download\256\50\www\res\icon\android\icon-48-mdpi.png';
$imginfo = getimagesize($image1);
header("Content-type: ".$imginfo['mime']);
readfile($image1);
$imginfo = getimagesize($image2);
header("Content-type: ".$imginfo['mime']);
readfile($image2);
?>
I could see the first image 'icon-36-ldpi.png' successfully read and displayed in the browser and the second image is not read and not displayed in the browser.
Am I missing something? Any advice please.
Sorry if I am doing stupid but the requirement is to read multiple image files and render in the browser like a grid view. I cannot use img tag because of security reasons.
You can't dump both images out at once. Why not make two images in your html so the browser makes two calls to your script. Then use a GET param to pass the filename you want to display.
---Edit---
Important Security Note
There is an attack vector which you open up when doing soething like this. Someone could easily view your source html and change the parameter to get your image script to output any file they want. They could even use "../../" to go up directories and search for well known files that exist. e.g. "../../../wp_config.php". Now the attacker has your wordpress database credentials. The correct way to prevent against this is to always validate the input parameter properly. For example, only output if the file name ends with ".jpg"

How to dynmically draw picture in php gd

Hi I have searched the web for 2 days but did not accomplish what I am looking for.
I have an apache server which will be accessed by 146 students. the user picks an angle from dropdown lets say 45 degress, then user clicks CALCULATE button. Then user clicks DIAGRAM button to see how the sine graph looks like.
Works like charm when i write the image to a file e.g: imagepng($img,"diagram.png");
Now the problem is that the diagram.png will always get overwritten by the last user. So for example if another user logs in and calculates the Sin 135. Both users will see Sine 135 because filename is hardcoded since there is conflict of filename.
I have searched the web on how to create the image dynamically instead of writing to a file and then reading the file. I have come across the following but not working:
base64_encode and decode
What would I have to do to my code of imagepng(...., ...) mentioned above to make use of base64 so I can actually draw the picture of already processed data. Let assume if I comment out the imagepng(..) code, then what do I replace it with. I hope I don't have to change my code a whole lot.
Please help
thanks
Amit
The filename argument to imagepng is optional. From the manual:
filename
The path to save the file to. If not set or NULL, the raw image stream will be outputted directly.
You would just need to send a png header at the top of the script and you would get the image as output for that script.
It's hard to tell without seeing you code how it is structured
but if once the user submits the form all you do is show the image by itself, then you can do something like this.
// make sure nothing else is out put before this otherwise it will stuff up the header
header('Content-Type: image/png);
imagepng($img);
If you embed the image into an html page as the result, then your best best would be to change the url of the image on the success page to something like this.
<img src="/path/to/file.php?deg=45" />
Then in the file.php
$deg = $_GET['deg'] + 0; // make sure it is a number
$img= function_render_graph($deg);
// make sure nothing else is out put before this otherwise it will stuff up the header
header('Content-Type: image/png);
imagepng($img);
By using a GET request, rather then a POST request then the image will likely be cached by the browser, so it doesn't need to be rendered each time. (Given that you have a drop list of angles, there must be a limited number of graphs that can actually be drawn)
Draw_Resultant_Prism_Graph (parameters)
{
$img = imagecreatetruecolor(800,750);
....
....
...
the following lines captures the data from output buffer and displays on same screen
***some version of IE have some issues mostly the dumb terminals where IE update is ADMIN
***restricted
ob_start();
header("Content-type: image/jpeg");
imagepng($img);
$output = ob_get_contents();
ob_end_clean();
imagedestroy($img);
echo img src="data:image/jpeg;base64,'.base64_encode($output).'"
user tags around img above and semicolon af
}

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.

PHP Image content type problem

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);
}
}

Categories