Displaying image with php - php

I have a script which displays images like this:
header("Content-Type: image/{$ext}");
readfile($image->path);
This has worked fine for weeks and now suddenly it has stopped working. The response header looks fine (Content-Type: image/jpg), I have no ending php-tag and I have made no changes to my code, server- or php-setup which could have caused this to malfunction. Does anyone have a clue as to what may be going wrong?
Thanks!
======================
UPDATE
The image doesn't display although you can download it (file->save as) and save it to computer. Openeing it locally though won't work either which leads me to think that the image has been corrupted somehow. Anyone experienced something similar? I'm thinking maybe som php errors/warnings get injected into the stream and corrupts the image.

One source of possible issues is that the MIME type for JPEG images is image/jpeg, not image/jpg. This is a case where the type doesn't agree with the fairly-common, 3-character version of the file extension.

Some thoughts:
File is to big
File path causing problems

The right content-type for JPG images is "Content-type: image/jpeg".
Note that the T of type is lower case.
UPDATE
I don't know if it will be useful but try something like this:
$info=pathinfo($image->path);
$ext=strtolower($info["extension"]);
if($ext=="jpg") $ext="jpeg";
header("Content-type: image/$ext");
imagejpeg(imagecreatefromjpeg($image->path));

Related

Saving images from sources without a specific mime type

As an example, say I'm trying to download App Icons from the Google Play store for a service. Here is an example URL:
https://lh6.ggpht.com/1eVPA6Iukw-F4i5xq1ZWicaKBzmprLGw98YhdG20E-wlsHHg3PcKJqbY_fWLdJeGRw=w512-rw
There is no mime type associated with the data provided, and when the file is saved any image viewers (or at least the ones I've tried) will say the file is corrupt. They will show up in Chrome and a couple of other things, but when inspecting the data, it's clear there's simply no mime type. This is an issue, because I am further using these data streams in other scripts which require that they be recognized as a specific type. (namely PNG)
I've tried things such as:
imagepng(imagecreatefromstring($icondata), $finaldir.'/icon.png');
Where $icondata is simply a curl response for the image. This will return an error saying that the data is of an unknown format for the imagecreatefromstring function. Of course, I've also tried:
file_put_contents($finaldir.'/icon.png', $icondata);
To no avail. It creates the file, but as I said, the image is not recognized as an image in most applications and in various analyzing functions. Is there a way to specifically set the mime type of a given string of data? Or some other workaround I'm not quite seeing?
Edit: Also, to note, there is nothing wrong with the $icondata variable. I have tried manually saving the image to a file through my web browser, and the same problem arises.
I have developed a small CMS for myself and was facing the same issue. After trying a lot, I have found a solution. It is working for me and I hope you will find it useful for your project too.
Regarding the corruption of file, for Chrome user-agent, Google servers send icons as .webp format and you need a PHP library for handling images of this type. And for other user-agents (like Firefox), images are sent as PNG.
Now comparing the two URLs for a same icon in Firefox or Chrome, you will notice that image paths generated for Chrome contain -rw at the end while the same URL in Firefox doesn't contain that -rw.
Not digging very deeper, simply remove the -rw from the end of the URL and copy the image. You will get a PNG image. A hint is here for you:
<?php
$image_path = "https://lh5.ggpht.com/8PODwBXKk4L201m4IO1wifRDfbn4Q1JxNxOzj-5TXPJ85_S-vOqntLi7TsVyeFQM0w4=w300-rw"; // Firefox app on Google Play
$png_path = substr($image_path, 0, -3);
copy($png_path, 'file.png');
?>
This will save the image as PNG. Please note that I have used substr() function to remove -rw from the end. To make it precise, you may use any other way to fix that part of the path.
P.S. You may also try sending a custom user-agent (i.e. Firefox) with your CURL request to receive the PNG path so you will not need to fix it by yourself :)
You can use HttpResponse::getContentType to determine type of content you're getting from URL
This not a png, but WebP
You can use it in PHP with
imagecreatefromwebp( string $filename );
More information:
- https://developers.google.com/speed/webp/
- http://php.net/manual/function.imagecreatefromwebp.php

PHP Media Link shows gibberish

Never done a lot of work with media files but I have an odd problem. I have a media link
http://.../wb_media/3343/64999/0aa2233675f94a4fc8a3915175e218f3/1/4e5b9927-3a46-4c69-9929-cc7e2a52f616.png
Which is suppose to show an image in the browser yet it shows gibberish:
Not sure where I should start looking to solve this? I have verified this is indeed the correct link. I would even appreciate knowing what that gibberish is called so I can research the problem more.
You must set header for the file type.
<?php
header("Content-type: image/png");
print (file_get_contents("location/to/image.png");
?>
Or if you are not printing it through php script, then you must look into server configuration. How server handles mime-types.

Why does this PHP tracking pixel not working correctly?

I'm working on setting up a simple pixel tracking script with PHP, and the below technically works, but when I look at the inspector in Safari I get the following warning (1by1.gif is a 42B gif):
esource interpreted as document but
transferred with MIME type image/gif.
header("Content-type: image/gif");
header("Content-Length: 42");
echo file_get_contents("/path/to/1by1.gif");
// do tracking stuff below here
I've looked at other tracking pixels, and they all show in the inspector as if they are an actual image, even with the .php extension. Any ideas how to fix that warning?
EDIT:
I tried doing the following and I get the same warning:
header("Content-type: image/gif");
$img = imagecreatefromstring(file_get_contents("/path/to/1by1.gif"));
imagegif($img);
You could write 1x1.gif (or some other made up name) in your HTML source and then have Apache actually serve the PHP script. You can do this with .htaccess with something along the lines of:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^1x1\.gif$ tracking_script.php [NC,L]
This way Safari sees the gif extension and won't complain.
Well this is interesting. If I remove the content-length and just use the following, it appears to work perfectly. Anyone know why that might be?
header("Content-type: image/gif");
echo file_get_contents("/path/to/1by1.gif");
// do tracking stuff below here
I'm a puzzled. Function file_get_contents() is for getting content from a text file. What is your intend here? The function returns the content as string or false. Your echo statement essentially transfers that result which is correctly interpreted as document and not a gif.
Update: Took me a while to even reproduce this and see the warning. Echoing the file_get_contents() shows indeed the gif in the browser, so does a simple include() which also shows the warning. Does this warning causes you any trouble or is this just for a beauty contest? I can only speculate that the Safari's Inspector is a little picky. The same tool in Chrome does not show a warning.
$img = imagecreatefromstring(file_get_contents("/path/to/1by1.gif"));
imagegif($img);
This code
Reads in a GIF image
Passes the image bytes to GD
Asks GD to write a new image.
Many things could go wrong here. For example, writing the image back out might not produce the same exact stream of bytes, maybe more, maybe less. This could make your Content-Length header invalid, and browsers don't like it when you lie about such stuff. Or maybe there's a Notice or Warning in one of the lines, which would be emitted as content before the GIF data. That would certainly look like a "document" instead of as image data to Webkit.
Serving the file through file_get_contents / include / echo eliminates the filter-through-GD step. If the code works properly without that step, the error was somewhere there.

Why getting image via PHP does not work?

I'm working with WampServer Version 2.0 on Windows XP and FireFox 3.6.8.
I'm trying to get image content via PHP script like this:
HTML:
<img src='temp_get_file.php' alt='picture not found' />
PHP: (temp_get_file.php)
<?php
header('Content-Type: image/png');
$img = imagecreatefromjpeg("1.png");
imagejpeg($img);
imagedestroy($img);
?>
The HTML, PHP, and 1.png files are located in the www directory of WampServer.
Unfortunately, I got this error (in HTTPFOX plugin in FireFox):
Error loading content (NS_ERROR_DOCUMENT_NOT_CACHED)
and I see "picture not found".
If I put the image in HTML directly like this:
<img src='1.png' alt='picture not found' />
everything works fine.
What's wrong with my PHP ?
This may just be a problem in your example, but this won't work:
imagecreatefromjpeg("1.png")
^ ^
JPEG != PNG
Not with your PHP actually but with your PHP skills :)
Some advises to improve
you have to debug your application instead of asking community.
To do so, you have to
a) request your image file directly, by typing temp_get_file.php into browsers address bar, to let you see output of the script
b) put Content-Type header output as low in the code, as possible, to let PHP sent text/html in case of some errors
c) have displaying errors on
or
instead of all this above you can turn logging errors on and catch the error in the error log.
both methods will let you to get PHP error message - a thing you really need here, instead of useless firefox complains.
and this error message is pretty clear - wrong file format.
if it's the only thing what your script does, you don't need all these GD functions. thats useless. if you need to output some file to the browser, just do it. readfile("1.png") is enough

TCPDF outputs weird characters in IE8

Today I started experimenting with PHP-based PDF generators. I tried TCPDF and it works fine for the most part, although it seems to be a little slow. But when I load the PHP file that generates my PDF in Internet Explorer 8, I see lines and lines of weird characters. Chrome however recognizes it as a PDF.
I'm assuming that I have to set a special MIME type to tell IE that it should interpret the page output as a PDF file. If yes, how can I do this?
putting "application/pdf" or "application/octet-stream" mime types might help. keep in mind that "application/octet-stream" will force download of the file and might prevent it from opening in the browser..
in case you wonder, you can do it like that:
header('Content-type: application/octet-stream');
I had this problem also but what I did to get it work is I added
exit();
at the end of pdf output.
You need to handle IE differently for dynamic-generated content. See this article,
http://support.microsoft.com/default.aspx?scid=kb;en-us;293792
In my code, I do this,
if(isset($_SERVER['HTTP_USER_AGENT']) AND ($_SERVER['HTTP_USER_AGENT']=='contype')) {
header('Content-Type: application/pdf');
exit;
}
This problem may also explain slowness you mentioned because your page actually sends the whole PDF multiple times without this logic.
#Pieter: I was experiencing the same issue using tcpdf (with fpdi), and loading the page that was generating the pdf using an ajax call. I changed the javascript to load the page using window.location instead, and the issue went away and the performance was much better. I believe that the other two posters are correct in the idea that the document header is causing the issue. In my case, because of the ajax call, the header was not being applied to the whole document, and causing the issue. Hope this helps.
I found this to be a problem too, and for me this all hinged on the code:
if (php_sapi_name( != 'cli') {
on line 7249 of the tcpdf.php file.
I commented this 'if' statement (and related '}')and all works fine for my other browser and ie8
Hope this helps

Categories