Force image download with php using header() in smartphones and tablets

JsStack picture JsStack · Oct 17, 2013 · Viewed 7k times · Source

I was searching already for a long time and I havent seen any right answer yet.

I'm trying to create a system in PHP where the user can download a signPicture that I create in JPG. The program is working fine in all desktop computers. There is not problem at all, even for IE8.

The header that I use:

header("Content-Type: application/octet-stream");
header('Content-Disposition: attachment; filename="test.jpg"');

in the end i just stream the picture:

imagejpeg($imgSign,NULL,100);

How I said, it's working really good in every browser. But then we get to the mobile devices, where in android for example, download a test.jpg file... but then it cannot open... and the same with ipad (actually doesnt download, it show the image in the browser and than I save it... but it does not open either).

I also try more examples that I saw, but doesnt change anything, like:

header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
header("Content-Type: application/force-download");
header("Content-Type: application/download");
header("Content-Transfer-Encoding: binary ");

Any idea how to sort this out in mobile devices?

Thanks!

Answer

JsStack picture JsStack · Oct 18, 2013

I got it!

There were differents problems. I found the clear solution in comments from this post: http://www.digiblog.de/2011/04/android-and-the-download-file-headers/

header("Content-Type: application/octet-stream");
header('Content-Disposition: attachment; filename="test.JPG"');

The important steps: I send everything with a form. The form, to make it work in mobiles, needs to have the target='_top' and the method='get'

It also make errors if the extention (jpg) is not in UPPERCASE and the file name is not between " ".

Now it works in all devices that I try by far. :)

Special thanks to Jörg Wagner, author of the post.