Hi everybody,

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.com/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.

I managed to get the image, and display it in another file within the tag. Eventually the remote access was turned off.

However when I try to send the ID of the image as a variable ex. image.php?img=1 it doesn't display within the tag in the file. Instead I get this when I click on the image source:

<title>302 Found</title>
<p>The document has moved <a href="http://www.somesite.com">here</a>.</p>

So basically I need a method to send the ID of the image from ex. showimage.php and I need image.php to retrieve it form "somesite dot com" and show it.

In your first example lets assume that $_GET was properly validated and tested to be a legitimate image filename, and another test to verify that the file exists, you could use the GD library.

Instead of the "file_get_contents()" line, use GD's methods: (search GD at php.net)

header("Content-type: image/jpeg");
// test that GET is set and add the path or set image path/name to a default image named "no-image.jpg"
$img = isset($_GET['img']) ? 'images/'.$_GET['img'] : 'images/no-image.jpg';

// good idea to test file existence
is_file($img) or die();

// make gd image object
$requested_image = imagecreatefromjpeg($img);
// stream out the image 
// do your chores and eat your vegetables

Might even test file name extensions which I didn't do in the example, NEVER TRUST DATA BEING SENT TO YOUR SCRIPTS, even if you *think* your other scripts are the only ones that should be making requests to these scripts, ALWAYS VALIDATE EVERYTHING!

I don't know if there are better libraries for image handling in PHP, but the GD library is the only one I am familiar with and it has worked very well for me.

I am only taking into consideration your first example where you are sending the image file name to the php script that will stream the image to the browser.

// Get an image based on id;
$id = $_GET;
$image = "Select image_field_name from $table_name where id = '$id' ";
$result = mysql_query($image);

//create an image
header('Content-type: image/jpeg');
$samp_image = imagecreatefromjpeg($result);

//display an image;

// Free up memory

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.