Search code examples
phpforce-download

php headers doesn't downloads


I was trying to make a "Force Download" via PHP, but all I get are strange symbols.

I tried to add the header ("application/typeofmyfile") and the header ("Content-Disposition")... and many others from many other post from here, but nothing

I've got this:

$f_location = "path/myfile.nl2pkg";
$f_name = "myfile.nl2pkg";


header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=".$f_name); //Here also tried basename($f_name) but nothing
header("Content-Length: ".filesize($f_location));    
header("Content-Transfer-Encoding: binary");

I'm doing it like this because when an user clicks on the "download" button, with ajax I send him to the page to force the download, put some data in the db and then refresh the main page.

It's my first time working on headers, and for I what read, don't know if I'm doing something wrong.


Solution

  • Your Headers Code seems fine. The problem seems to be somewhere else.

    To debug your Code use headers_sent to determine if headers already have been sent. You can also use headers_list to see what headers have already been sent.

    if (headers_sent()) {
      var_dump(headers_list());
      die('Headers have already been sent');
      exit;
    }
    

    If you use this right before you define the headers you will probably find the source of your problem.