Php: Force File Download and Ie, Yet Again

PHP: Force file download and IE, yet again

This will check for versions of IE and set headers accordingly.

// assume you have a full path to file stored in $filename
if (!is_file($filename)) {
die('The file appears to be invalid.');
}

$filepath = str_replace('\\', '/', realpath($filename));
$filesize = filesize($filepath);
$filename = substr(strrchr('/'.$filepath, '/'), 1);
$extension = strtolower(substr(strrchr($filepath, '.'), 1));

// use this unless you want to find the mime type based on extension
$mime = array('application/octet-stream');

header('Content-Type: '.$mime);
header('Content-Disposition: attachment; filename="'.$filename.'"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: '.sprintf('%d', $filesize));
header('Expires: 0');

// check for IE only headers
if (preg_match('~MSIE|Internet Explorer~i', $_SERVER['HTTP_USER_AGENT']) || (strpos($_SERVER['HTTP_USER_AGENT'], 'Trident/7.0; rv:11.0') !== false)) {
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
} else {
header('Pragma: no-cache');
}

$handle = fopen($filepath, 'rb');
fpassthru($handle);
fclose($handle);

Force download with PHP then redirect

  1. You can't hide a file location. It'll be plainly visible to anybody determined enough to find it, by the very necessity that the browser needs to know the URL to download the file.
  2. You can't do it with two header redirects in succession, as you said. You can only redirect to a different page after some timeout using Javascript.

There really isn't much choice. If your primary goal is to hide the URL, that's a lost cause anyway. For good usability, you usually include the plain link on the page anyway ("Download doesn't start? Click here..."), since the user may accidentally cancel the redirect at just the wrong time to irrevocably kill the download.


You cannot output anything other than the file itself in the same request/response. You could try multi-part HTTP responses as suggested by @netcoder, but I'm not really sure how well that's supported. Just start with the assumption that there's one "wasted" request/response in which only the file is downloaded and nothing else happens. The way things usually work with this restriction is like this:

  • User clicks "download" link or submits form with his email address or whatever is required to initiate the download process.
  • Server returns the "Thank you for downloading from us! Your download will start shortly..." page.
  • This page contains Javascript or a <meta> refresh or HTTP Refresh header that causes a delayed redirect to the URL of the file.
  • The "Thank you" page will "redirect" to the file location, but since this causes the file to download, the page will not visibly change, only the download will be initiated.

Look at http://download.com for an example of this in action.

You can make the download location for the file be a script that only returns the file if the user is allowed to download the file. You can pass some temporary token between the "Thank you" page and the file download page to verify that the download is allowed.

Protecting / serving a file via readfile(), force download?

You need to set the appropriate header for whatever the file type is. For example, if readfile always serves, PDFs, it should be done like this:

// disable browser caching -- the server may be doing this on its own
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");

header('Content-Type: application/pdf');
//forces a download
header("Content-Type: application/force-download");
header('Content-Disposition: attachment; filename=filename.pdf');
readfile($file);

Keep in mind that header only works if you have not sent any data in the request at all including whitespace.

php file force download

I've had a chance to work it out. Your problem is two-fold.

First, remove the www. from the url.

Second, remove the call to filesize($file) which is throwing an error because PHP doesn't know the size of the file before it downloads the file. (really, just remove the whole line)

Removing these two things, I was successful.

Idiot-proof, cross-browser force download in PHP

So, I used this code (It's modified version of resumable http download found on internet)

function _output_file($file, $path)
{
$size = filesize($path.$file);

@ob_end_clean(); //turn off output buffering to decrease cpu usage

// required for IE, otherwise Content-Disposition may be ignored
if(ini_get('zlib.output_compression'))
ini_set('zlib.output_compression', 'Off');

header('Content-Type: application/force-download');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header("Content-Transfer-Encoding: binary");
header('Accept-Ranges: bytes');

/* The three lines below basically make the
download non-cacheable */
header("Cache-control: no-cache, pre-check=0, post-check=0");
header("Cache-control: private");
header('Pragma: private');
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");

// multipart-download and download resuming support
if(isset($_SERVER['HTTP_RANGE']))
{
list($a, $range) = explode("=",$_SERVER['HTTP_RANGE'],2);
list($range) = explode(",",$range,2);
list($range, $range_end) = explode("-", $range);
$range=intval($range);
if(!$range_end) {
$range_end=$size-1;
} else {
$range_end=intval($range_end);
}

$new_length = $range_end-$range+1;
header("HTTP/1.1 206 Partial Content");
header("Content-Length: $new_length");
header("Content-Range: bytes $range-$range_end/$size");
} else {
$new_length=$size;
header("Content-Length: ".$size);
}

/* output the file itself */
$chunksize = 1*(1024*1024); //you may want to change this
$bytes_send = 0;
if ($file = fopen($path.$file, 'rb'))
{
if(isset($_SERVER['HTTP_RANGE']))
fseek($file, $range);

while
(!feof($file) &&
(!connection_aborted()) &&
($bytes_send<$new_length) )
{
$buffer = fread($file, $chunksize);
print($buffer); //echo($buffer); // is also possible
flush();
$bytes_send += strlen($buffer);
}
fclose($file);
} else die('Error - can not open file.');

die();
}

and then in model:

function download_file($filename){
/*
DOWNLOAD
*/
$path = "datadirwithmyfiles/"; //directory

//track analytics

include('includes/Galvanize.php'); //great plugin
$GA = new Galvanize('UA-XXXXXXX-7');
$GA->trackPageView();

$this->_output_file($filename, $path);

}

It works as expected in all mentiond browser on Win / MAC - so far, no problems with it.

Mp3 Download not functioning

Take a look at this thread, I had similar problems: PHP: Force file download and IE, yet again. Also consider using Fiddler to capture the exact HTTP headers that are being sent to the client.

PHP file download not recognizing file type in Chrome and Edge

can you try:

header("Content-Disposition: attachment; filename=\"$title\".mp3");

to see if the title does not contain the extension



Related Topics



Leave a reply



Submit