Force to download image from external server - php

I want to implement a button that downloads an image uploaded in a external server.
HTML 5 download attribute does work, but in FireFox and IE10 it opens the image in a new window and the user still have to use the right click to save image as.
Save
I can force the download using PHP if the image is located in my server.
<?php
$file = $_GET['file'];
download_file($file);
function download_file( $fullPath ){
// Must be fresh start
if( headers_sent() )
die('Headers Sent');
// Required for some browsers
if(ini_get('zlib.output_compression'))
ini_set('zlib.output_compression', 'Off');
// File Exists?
if( file_exists($fullPath) ){
// Parse Info / Get Extension
$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);
$ext = strtolower($path_parts["extension"]);
// Determine Content Type
switch ($ext) {
case "png": $ctype="image/png"; break;
case "jpeg":
case "jpg": $ctype="image/jpg"; break;
default: $ctype="application/force-download";
}
header("Pragma: public"); // required
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
header("Content-Type: $ctype");
header("Content-Disposition: attachment; filename=\"".basename($fullPath)."\";" );
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".$fsize);
ob_clean();
flush();
readfile( $fullPath );
} else
die('File Not Found');
}
?>
HTML
Download1
Is there a way to avoid with the HTML5 download attribute the problem to open the image in a new window in FF and IE? -Chrome works great-.
Is there a way to do it with PHP but when the image is located at and external server?
It will be great to do it any way, HTML 5 or PHP. Thanks for any help. Greetings.

Copy it to your server and download from there.
file_put_contents($fullpath,
file_get_contents('https://externalserver/images/image.png'));
header("Pragma: public"); // wtf?
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
// omg what have you been reading?
header("Cache-Control: private",false);
// obviously not rfc 2616
header("Content-Type: $ctype");
header("Content-Disposition: attachment; filename=\"".basename($generatedPath)."\";" );
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".$fsize);
ob_clean();
flush();
readfile( $fullPath );

For the php part. If you have the URL of the image you can use many approach.
An easy one would be a simple call to file_get_content to retrieve the image binary data in a variable .
After you can save it to the disk or do whatever you want with it.

Related

Force Download Images using PHP

I am trying to download an image from website using php with the following code.
Currently it idendtify and downloads the file. but the
file downloaded is not opening and it shows as corrupted. what is the issue in the below code ?
Also I am embedding this page in one of my mobile app. will it work in mobile android devices too
<?php
$file = "http://example.com/animals/1.jpg";
// Parse Info / Get Extension
$fsize = filesize($file);
$path_parts = pathinfo($file);
$ext = strtolower($path_parts["extension"]);
// Determine Content Type
switch ($ext)
{
case "gif": $ctype="image/gif"; break;
case "png": $ctype="image/png"; break;
case "jpeg":
case "jpg": $ctype="image/jpg"; break;
default: die('Wrong Extension');
}
header("Pragma: public"); // required
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private", false); // required for certain browsers
header("Content-Type: $ctype");
header("Content-Disposition: attachment; filename=\"Test".basename($file)."\";" );
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . $fsize);
ob_clean();
flush();
readfile($file);
exit();
?>
You need to send data stream to browser.
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream'); // change this will work for you.
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;

not able to download or open blank PDF file PHP

I am facing some problems while generating PDF reports from my application in firefox(ubuntu machine).
my code is:
<?php
$path = "path_to_file" ;
$file = "test.pdf";
header('Content-type: application/pdf');
header("Content-disposition: attachment; filename=$file");
readfile($path);
return new Response("Success");
code is working:
when the PDF-report contains data
when size is more than 1 kb
In windows machine
not working:
when report contains no data or size is in bytes.
It is Generating a binary sting in a new tab in browser instead of generating blank-PDF.
Please help me fixing this issue.Thanks in advance.
Got my answer.This may help others.
<?php
$path = "path_to_file" ;
$file = "test.pdf";
header("Content-disposition: attachment; filename= $file"); //Tell the filename to the browser
header("Content-type: application/pdf");//Get and show report format
header("Content-Transfer-Encoding: binary");
header("Accept-Ranges: bytes");
readfile($path); //Read and stream the file
get_curret_user();
I would do it in this way to avoid some problems with browser applications and caching. Give it a try:
<?php
$path = "path_to_file" ;
$file = "test.pdf";
$content = file_get_contents($path);
header("Content-disposition: attachment; filename=\"".$file."\"");
header("Content-type: application/force-download");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".strlen($content));
header("Pragma: no-cache");
header("Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
header("Expires: 0");
echo $content;
die();
EDIT:
If it's really necessary to use the pdf plugin of the browser instead of downloading and opening it immediately with the associated default pdf reader, please replace
header("Content-type: application/force-download");
with
header("Content-type: application/pdf");

php download fails on large files

I'm trying to get a link to download files without redirecting, or using another file to download large zip files.
It works great for files under ~100mb, but anything larger and it's sent to an error page in chrome that says: Error code: ERR_INVALID_RESPONSE.
The $file and $path are put into a form with jQuery, and then $('form').submit(); is called.
function downloadFile($file, $path){
set_time_limit(0);
$fullPath = $path . $file;
if ($fd = fopen ($fullPath, "r")) {
$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);
$ext = strtolower($path_parts["extension"]);
switch ($ext) {
case "pdf":
header("Content-type: application/pdf"); // add here more headers for diff. extensions
header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\""); // use 'attachment' to force a download
break;
default;
header("Content-type: application/octet-stream");
header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
}
header("Content-length: $fsize");
header("Cache-control: private"); //use this to open files directly
while(!feof($fd)) {
$buffer = fread($fd, 2048);
echo $buffer;
}
}
fclose ($fd);
exit;
}
Any ideas why it fails on larger files?
Update:
When I use the following code, it downloads the file, but the finished file doesn't open as it's corrupted for some reason:
set_time_limit(0);
ini_set('memory_limit', '1024M');
// http headers for downloads
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"".$filename."\"");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".$file_size);
ob_end_flush();
#readfile($fileinfo['path']);
When I use this code, it only downloads the first 49.7kb then says it's finished, I even tried ob_flush() and flush() together:
// http headers for downloads
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"".$filename."\"");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($fileinfo['path']));
if ($fd = fopen ($fileinfo['path'], "r")) {
set_time_limit(0);
ini_set('memory_limit', '1024M');
while(!feof($fd)) {
echo fread($fd, 4096);
flush();
}
}
The only thing I do different in my downloader is Content-Transfer-Encoding: chunked. Also take the flush() out of the loop and make sure you do ob_clean(); flush(); before and ob_end_flush(); after sending the data.

unknown file format on image download in php

i have this code for image download in php... works fine, image downloads but the problem is that it does not open in the place where it gets downloaded, and gives the error " Can't read file header...Unknown file format! "
<?php
$path = $row['img_url'].".jpg";
echo $path;
$filename = $path;
$ctype="application/.jpg";
// required for IE, otherwise Content-disposition is ignored
if(ini_get('zlib.output_compression'))
ini_set('zlib.output_compression', 'Off');
header("Pragma: public"); // required
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false); // required for certain browsers
header("Content-Type: $ctype");
// change, added quotes to allow spaces in filenames
header("Content-Disposition: attachment; filename=\"".basename($filename)."\";" );
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($filename));
readfile("$filename");
exit();
?>
Change the content type
$ctype="application/.jpg"; //It's a invalid content type
to
$ctype="image/jpeg";
you should not be echoing anything before the header and try using header('Content-Type: image/jpeg');
Try using image/jpeg MIME type instead of application/.jpg
Your content type is wrong. Try to use $ctype="image/jpeg";

Force downloading an image via php script works but the image only opens in paint not photoshop

Here is my php script which executes the download:
$link = 'www.example.com';
$url = urlencode($link);
$image = "http://chart.googleapis.com/chart?chs=75x75&cht=qr&chl=$url&choe=UTF-8&chld=L|0";
$filename = file_get_contents("$image");
header("Pragma: public");
header("Expires: 0"); // set expiration time
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Disposition: attachment; filename='qr code';");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($filename));
echo $filename;
This downloads a file but it only opens in paint not photoshop. As a hint there doesn't appear to be a file type associated with the file (e.g. png or jpg).
I need all the headers above so this works in all browsers.
Thanks.
Perhaps pass a file extension in your filename header.
header("Content-Disposition: attachment; filename='qr_code.jpg';");

Categories