php - How to force download of a file?

You could try something like this:

$file_name = 'file.avi';
$file_url = 'http://www.myremoteserver.com/' . $file_name;
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary"); 
header("Content-disposition: attachment; filename=\"".$file_name."\""); 
readfile($file_url);
exit;

I just tested it and it works for me.

Please note that for readfile to be able to read a remote url, you need to have your fopen_wrappers enabled.


Tested download.php file is

function _Download($f_location, $f_name){
  $file = uniqid() . '.pdf';

  file_put_contents($file,file_get_contents($f_location));

  header('Content-Description: File Transfer');
  header('Content-Type: application/octet-stream');
  header('Content-Length: ' . filesize($file));
  header('Content-Disposition: attachment; filename=' . basename($f_name));

  readfile($file);
}

_Download($_GET['file'], "file.pdf");

and the link to download is

<a href="download.php?file=http://url/file.pdf"> Descargar </a>

Try this:

<?php
$FileName = '/var/ww/file.txt';
header('Content-disposition: attachment; filename="'.$FileName.'"');
readfile($FileName);

The key is the header(). You need to send the header along with the download and it will force the "Save File" dialog in the user's browser.