How to force file download with PHP

04/11/2020 16:30:01

I want to require a file to be downloaded upon the user visiting a web page with PHP. I think it has something to do with file_get_contents, but am not sure how to execute it.

$url = "";

After downloading a file with header(location) it is not redirecting to another page. It just stops.

Answer #1 (223 Votes)

09/01/2011 02:54:40

Read the docs about built-in PHP function readfile

$file_url = '';
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary"); 
header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\""); 

Also make sure to add proper content type based on your file application/zip, application/pdf etc. - but only if you do not want to trigger the save-as dialog.


Answer #2 (39 Votes)

09/01/2011 02:54:42
$file = ""; 

header("Content-Description: File Transfer"); 
header("Content-Type: application/octet-stream"); 
header("Content-Disposition: attachment; filename=\"". basename($file) ."\""); 

readfile ($file);

Or, when the file is not openable with the browser, you can just use the Location header:

<?php header("Location:"); ?>
Hack Hex uses Stack Exchance API by the Stack Exchange Inc. to scrape questions/answers under Creative Commons license.