Page 1 of 1

forcing image download with php header

Posted: Mon Nov 02, 2009 10:55 am
by 10lojzo
Hi, I use script to force browser to popoup save dialog on image click:

Code: Select all

 
<?php
$image = $_GET['file'];
header('Content-disposition: attachment; filename='.basename($image));
header('Content-type: image/jpeg');
readfile($image);
?>
 
Everything works fine. after clicking on image link you can download it. I use AcDsee to open images and i can preview the downloaded image, but the image seems to be corrupted when trying to open in another picture viewer. What i found out is that after downloading the image, the format of the file is changed. Originally the jpeg file is stored on server in ANSI format but after downloading it is stored in utf-8 format(still it is jpeg file). After changing format of the file back to ANSI in some editor(e.g notepad++) everything works fine. I played with headers a lot (changing content-type header, adding various charset values, even charset of my webpage etc) to no avail. Do you have any idea what is wrong? Thanks

-- Martin

Re: forcing image download with php header

Posted: Tue Nov 03, 2009 12:05 am
by McInfo
It is important to filter user input. As your script is now, you are allowing users to download any file that is accessible to your script. This gives users access to the source code of your PHP files and other private data.

As for your formatting problem, you could try creating an image resource with imagecreatefromjpeg() or one of the other imagecreatefrom*() functions and output the image with imagejpeg().

Edit: Try this too.

Code: Select all

header('Content-Transfer-Encoding: binary');
Edit: This post was recovered from search engine cache.

Re: forcing image download with php header

Posted: Tue Nov 03, 2009 6:36 am
by 10lojzo
McInfo

Thank you for your reply. I will consider the security issue you commented on. As for the charset problem i figured it out. I have my images ready on the server in jpeg or png format so imagejpeg() or imagecreatefromjpeg() is not an option for me.

adding header('Content-Transfer-Encoding: binary') was not helpful either, nor was changing header('Content-type: image/jpeg') to header('Content-Type: application/octet-stream');

Script i provided in my previous post is stored in simple php file and this file had utf-8 format. I had to change it to ansi format and now everything works like a charm. Trivial enough but cost me time and nerves :).

Re: forcing image download with php header

Posted: Tue Nov 03, 2009 12:56 pm
by McInfo
10lojzo wrote:I have my images ready on the server in jpeg or png format so imagejpeg() or imagecreatefromjpeg() is not an option for me.
The imagecreatefrom*() functions create image resources from files, so I don't understand why it wouldn't be an option.

I'm glad you figured out a solution to your problem, though.

Edit: This post was recovered from search engine cache.