Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP force download not working?

On my HTML page I have made a JQuery ajax request to a php script that should force a download, but nothing is happening?

On my html page (in click event handler for a link)...

var file = "uploads/test.css";
$.ajax(
{
    type      : "POST",
    url       : "utils/Download_File.php",
    data      : {"file":file}
})

And the Download_File.php script looks like this

<?php

Download_File::download();

class Download_File
{
    public static function download()
    {
        $file = $_POST['file'];

        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment');
        readfile('http://localhost/myapp/' . $file);
        exit;
    }
}
?>

But nothing is happening for some reason? I looked at the response headers in firebug and cant see any problems. Im using Xampp. Any help is much appreciated.

Thanks!

like image 610
Rory Avatar asked Jan 26 '11 21:01

Rory


1 Answers

You should specify the Content-Transfer-Encoding. Also, you should specify the filename on your Content-Disposition.

header('Content-Type: application/octet-stream');
header('Content-Transfer-Encoding: binary');
header('Content-Disposition: attachment; filename="'.$file.'"');
readfile('http://localhost/myapp/'.$file);
exit;

It's important to include double-quotes around the filename as this is required by RFC 2231. Firefox is known to have problems downloading files that have spaces in the file name if the filename is not in quotes.

Also, check to make sure there is no white space after your closing ?>. If even a space exists after the closing PHP tag, the headers won't be sent to the browser.

As a side note, if you have a number of common file types you're going to offer for download, you might consider specifying those MIME types. This provides a better experience for the end user. For example, you could do something like this:

//Handles the MIME type of common files
$extension = explode('.', $file);
$extension = $extension[count($extension)-1];
SWITCH($extension) {
  case 'dmg':
    header('Content-Type: application/octet-stream');
    break;
  case 'exe':
    header('Content-Type: application/exe');
    break;
  case 'pdf':
    header('Content-Type: application/pdf');
    break;
  case 'sit':
    header('Content-Type: application/x-stuffit');
    break;
  case 'zip':
    header('Content-Type: application/zip');
    break;
  default:
    header('Content-Type: application/force-download');
    break;
}
like image 66
Michael Irigoyen Avatar answered Sep 20 '22 02:09

Michael Irigoyen