Search code examples
phpdownloadremote-server

php - How to force download of a file?


I'm looking to add a "Download this File" function below every video on one of my sites. I need to force the user to download the file, instead of just linking to it, since that begins playing a file in the browser sometimes. The problem is, the video files are stored on a separate server.

Any way I can force the download in PHP?


Solution

  • You could try something like this:

    <?php
    
    // Locate.
    $file_name = 'file.avi';
    $file_url = 'http://www.myremoteserver.com/' . $file_name;
    
    // Configure.
    header('Content-Type: application/octet-stream');
    header("Content-Transfer-Encoding: Binary"); 
    header("Content-disposition: attachment; filename=\"".$file_name."\"");
    
    // Actual download.
    readfile($file_url);
    
    // Finally, just to be sure that remaining script does not output anything.
    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.