I want to have a PNG picture, but when accessing it, it runs a PHP script, the PHP script should decide what picture to send (using some if statements and whatever). Then the PHP script should read the image file from somewhere on my web server and output it.
Here is the issue, if I get a .png file, and put PHP code in it, it won't work, however, if I use the .php extension, it works, and I can even embed the image into other websites, and the PHP can decide what image to send, but if I want to view that image directly (copy it's URL into my address bar) it doesn't work, it gives me the images plain contents (random jibberish).
Anyone know what to do?
Also This is my first question on Stack Overflow - please tell me if I am doing something wrong.
You need to send Content-Type headers.
For png:
header('Content-Type: image/png');
For others change png to jpg or gif or bmp or whatever.
Please note that header() function must be used before anything is written to output.
First, make sure you have your image image.png somewhere accessible to php.
Then create a php script image.php:
<?php
header('Content-Type: image/png');
readfile('image.png');
The script now acts like it was a PNG image.
It sounds like you know how to send the image, your issue is that you want the URL to look like it's a PNG image.
There are a couple of things you can do. First, if your web server supports URL rewriting (like Apache's mod_rewrite module), you can use a rewrite rule so that the user access the script as something like http://example.com/generated_image.png but your server will translate/rewrite this URL to point directly to your PHP script, so something like /var/www/image_generator.php.
Another option would be to actually name your script "generated_image.png" but force your webserver to treat it like a PHP script. For instance, in Apache you could try something like:
<Location /generated_image.png>
ForceType application/x-httpd-php
</Location>
As a final note, if you're not actually worried about the URL, but worried about the file name that is used if the user decides to save it to disk, you can simply use the Content-Disposition HTTP header in your response. In PHP it would look something like this:
<?php
header("Content-Disposition: inline; filename="generated_image.png");
?>
With that, it doesn't matter what the URL is, if the user saves the image through their web browser, the web browser should offer "generated_image.png" as the default filename.
Simplest version I know...
<?php
header('Content-Type: image/png');
if(whatever)
{
$image=your_image_select_function();
}
// as suggested by sh1ftst0rm with correction of unmatched quotes.
header('Content-Disposition: inline; filename="'.$your_name_variable.'"');
readfile($image);
?>
Then, you treat it like an image file. That is, if this is "pngmaker.php" then, in your HTML document, you do
<img src="pngmaker.php">
You can even do
<img src="pngmaker.php/?id=123&user=me">
Related
Trying to see what actions can be performed with a PHP script that is being called via an image src like so:
<img src="http://example.com/script.php" />
Now, I have tried to include the PHP header() function in script.php:
<?php
header("Location: http://example.com");
I have also tried to echo an image url expecting the img to display it, which it didn't:
<?php
echo 'http://example.com/image.png';
Are there any ways of doing such things with a PHP script that is being called in the img src attribute?
Are there any ways of doing such things with a PHP script that is being called in the img src attribute?
No. A resource that is used as a src for an img tag needs to output image data, nothing else.
There are some exceptions, eg. a header("location: ....") redirect, but the redirect needs to point to another valid image resource, not a web site as you show in your example.
Check out the readfile() as a way to output your image file from your script.php
readfile($file);
Read more about it here in the manual:
http://php.net/manual/en/function.readfile.php
where Example #1 gives an idea of how to set up the headers.
The manual also states that:
readfile() will not present any memory issues, even when sending large
files, on its own.
and
A URL can be used as a filename with this function
ps: This was the way Wordpress Multisite used to open user uploaded (e.g. images) files.
Your script.php should return the output of an image with the correct headers. For instance:
<img src="/html/img/script.php" />
// Script.php
$file = "tiger.jpeg";
$type = "image/jpeg";
header("Content-Type: $type");
header("Content-Length: " . filesize($file));
readfile($file);
You should keep in mind that the src tag should directly point to an image file. However, it is possible to use PHP to create an image, for exmaple by using the GD library:
http://php.net/manual/en/book.image.php
So using:
<img src="http://example.com/script.php" />
is possible, as long as script.php really outputs an image file, for example by using the example as described here:
http://www.php.net/manual/en/image.examples-png.php
I used this kind of processing in the past to overlay texts on JPG images for a broker website (e.g. new, sold, for rent, etc.).
Are there any ways of doing such things with a PHP script that is being called in the img src attribute?
Yes, but the PHP Script has to output image data only, as stated in various other answers.
With that being said, just read the image and output it to the stream with readfile
header('Content-Type: image/png');
readfile($file);
exit();
I know I might be a couple years late to really help you, but the accepted answer just isn't true (anymore).
My site uses bookmarklets to gather data from external sites, kinda like Pinterest. I'm concerned about security and want to move the images the bookmarklet gathers from the doc root up one level. My script has some hefty security checks in place, but I want to add this as a last line of defense.
How do I access my images within my script? Obviously using ../userimages/id/image.jpg wont work. I'm using Apache.
Thanks!
Proxy the image
You would use a proxy script to feed the images through like the following example:
// open the file in a binary mode
$name = '../userimages/id/image.jpg';
$fp = fopen($name, 'rb');
// send the right headers
header("Content-Type: image/png");
header("Content-Length: " . filesize($name));
// you may like to set some cache headers here
// dump the picture and stop the script
fpassthru($fp);
exit;
This example is from the PHP manuals fpassthru() page. You would save this script somewhere in your servers document root/httpdocs folder.
"Spoofing" the URL to the image
The easiest way to give the PHP file the appearance of being an image file to a user/browser is to use Apaches mod_rewrite. Usually I use a URL structure something like this:
http://www.example.org/image-id/image.png
Where image-id is the unique identifier for that particular image. This way the file has the correct extensions of an image instead of .php.
I have a page in my site, displaying some images that are produced my PHP. When I right click on an image and click Save Image As I get as default name the name of the php file used for generating the image.
This is for example the html for the image :
<img src="picture_generator.php?image_id=5&extension=.png">
and the name I get is:
picture_generator.php.png
Is there a way to set this name to a default one?
Thanks in advance
You can provide it in the Content-Disposition HTTP header:
header('Content-Type: image/png');
header('Content-Disposition: inline; filename="' . $filename . '"');
However, some browsers (namely Internet Explorer) are likely to ignore this header. The most bullet-proof solution is to forge the URL and make the browser believe it's downloading a static file like /images/5/foo.png while the actual path behind the scenes is /picture_generator.php?image_id=5&extension=.png. This can be accomplished by some web server modules like Apache's mod_rewrite.
You can try to set the file name using the HTTP headers but not all browsers respect that.
The simplest trick is to extend the URL so that the last part contains the desired file name:
<img src="picture_generator.php/desiredfilename.jpg?image_id=5&extension=.png&name=desiredfilename.jpg">
Note I also added the file name at the end of the query string (the name doesn't really matter) as some browsers use that part.
Depending on your server configuration this will immediately work without any special configuration (no mod_rewrite or anything like that). You can check if it works on your server by simply appending "/foo" to any PHP-URL on your site. If you see the output of your PHP, all is good. If you see a 404 error then your server configuration can't deal with such URLs.
In your picture_generator.php file you need to add a header with the name. such as
header("Content-Disposition: attachment; filename=\"myfile.png\"");
I want code that loads an image to a PHP server and then send it to browser.
For example I want sample.php to send an image to browser once it is requested.
in other words, I want to create a PHP file that acts like a proxy for an image.
why are you doing this?
why don't deliver the image directly?
if you are trying to display a random image you may as well just redirect to the image using
header("Location: address-of-image");
for delivering the file to your clients from your server and not from its original location you can just do. however your php.ini settings need to allow external file opens
readfile("http://www.example.com/image.jpg")
correct headers are not required if you are going to display the image in an img tag,
altough i would recommend it. you should check the filetype of the image or in most cases just set an octet-stream header so the browser doesnt assume an incorrect type like text or something and tries to display binary data.
to do so just do
header("Content-type: application/octet-stream")
one more thing to consider may be setting correct headers for caching...
You need to use
$image = fopen("image.png");
Modify the headers(not sure exacly if it's correct)
headers("Content-type: image/png");
And then send the image
echo fread($image, file_size("image.png"));
I am trying to display an image from a MySQL blob field. I have tried a few different things and none of them seem to work.
I have tried:
header("Content-type: $type"); img src = $blobData;
header("Content-type: $type"); echo($blobData);
<?php
header("Content-type: $type");
echo $blobData;
?>
This code looks perfectly OK. However, I heard a similar complain from another person and I was able to troubleshoot it by assuring that:
The php script does not output any extra character before or after sending the binary image data.
The php script is saved as a pure ASCII text file, not as a Unicode/UTF-8 encoded file. The Unicode/UTF-8 encoded PHP files might include a signature as the first bytes. These bytes will be invisible in your text editor but server will send these few extra bytes to the browser before the JPEG/GIF/PNG data. The browser will therefore find the wrong signature in the beginning of data. To workaround, create a blank text file in notepad, paste in the php code and save the file in ANSI encoding.
Another option you might consider (assuming you are on Apache):
Create an .htaccess file with a mod_rewrite for all image extensions (png, jpg, gif).
Have it redirect to a php script that looks up the image requested in the DB. If it is there, it echos out the header and BLOG. If it isn't there, it returns a standard 404.
This way you can have:
<img src="adorablepuppy.jpg" />
Which then gets redirected ala:
RewriteEngine on
RewriteRule \.(gif|jpg|png)$ imagelookup.php
This script does a query for the image, which (obviously) assumes that the requested image has a unique key that matches the filename in the URL:
$url = $_SERVER['REQUEST_URI'];
$url_parts = explode("/", $url);
$image_name = array_pop($url_parts);
Now you have just the image filename. Do the query (which I shall leave up to you, along with any validation methods and checks for real files at the address, etc.).
If it comes up with results:
header('Content-type: image/jpeg');
header('Content-Disposition: inline; filename="adorablepuppy.jpg"');
print($image_blog);
otherwise:
header("HTTP/1.0 404 Not Found");
FYI: I have no idea if this would be bad in terms of performance. But it would allow you to do what I think you want, which is output the image as though it were a flat image file on the server using a simple image element. I'm inclined to agree that BLOBs are not the best way to go, but this does avoid any cross-browser issues.
I believe that the issue that you are encountering is an issue with encoding. This resource claims that you can use the print function.
Just get the image from the database. And print it using the correct headers.
$image = mysql_fetch_array(...)
header("Content-type: image/jpeg"); // change it to the right extension
print $image['data'];
For performance reasons... this is not advisable. There are several reasons to put images in databases but the most common are:
a) keeping them indexed (duh!)
You can do this by storing the images flat on the server and just indexing the image filename.
b) keeping the image hidden/protected
Flickr and alike still store the images flat on the server and use a different approach. They generate a URL thats hard to find.
This link points to a protected image on my account. You can still access it once you know the correct URL. Try it!
farm2.static - a farm optimized for delivering static content
1399 - perhaps the server
862145282 - my username
bf83f25865_b - the image
In order to find all my secret images any user can hard hit Flickr with the above address and change the last part. But it would take ages and the user would probably be blocked for hammering the server with thousands of 404s.
That said there is little reason to store images on BLOBs.
Edit:Just a link pointing to someone that explained much better than I did why BLOB is not the way to go when storing images.