148

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 = "http://example.com/go.exe";

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
john
  • 1,507
  • 2
  • 10
  • 6
  • possible duplicate of [forcing page download in php](http://stackoverflow.com/questions/2106709/forcing-page-download-in-php) – hakre Oct 19 '13 at 12:54
  • possible duplicate of [Forcing to download a file using PHP](http://stackoverflow.com/questions/1465573/forcing-to-download-a-file-using-php) – user May 15 '14 at 05:57
  • check out the answers here https://stackoverflow.com/questions/18661416/download-file-from-server-to-clients-system-via-php as well. – DrBeco Jun 04 '23 at 16:53

12 Answers12

281

Read the docs about built-in PHP function readfile

$file_url = 'http://www.myremoteserver.com/file.exe';
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary"); 
header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\""); 
readfile($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.

Pit Digger
  • 9,618
  • 23
  • 78
  • 122
59
<?php
$file = "http://example.com/go.exe"; 

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

readfile ($file);
exit(); 
?>

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

<?php header("Location: http://example.com/go.exe"); ?>
Kerem
  • 11,377
  • 5
  • 59
  • 58
Marek Sebera
  • 39,650
  • 37
  • 158
  • 244
42
header("Content-Type: application/octet-stream");
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"file.exe\""); 
echo readfile($url);

is correct

or better one for exe type of files

header("Location: $url");
psukys
  • 387
  • 2
  • 6
  • 20
genesis
  • 50,477
  • 20
  • 96
  • 125
  • @Fabio: Will add more detials – genesis Aug 31 '11 at 21:59
  • That was super easy. It worked. What is file-Get_contents for then? Just curious. Thanks. – john Aug 31 '11 at 22:00
  • to download it to your server – genesis Aug 31 '11 at 22:01
  • 10
    Just remove 'echo' prior to 'readfile()' since the return value is specified as "Returns the number of bytes read from the file. If an error occurs, FALSE is returned and unless the function was called as @readfile(), an error message is printed.". So you'll end up with the content of the file + integer number at the end of the content. – Mladen B. Jun 28 '13 at 08:08
27

Display your file first and set its value into url.

index.php

<a href="download.php?download='.$row['file'].'" title="Download File">

download.php

<?php
/*db connectors*/
include('dbconfig.php');

/*function to set your files*/
function output_file($file, $name, $mime_type='')
{
    if(!is_readable($file)) die('File not found or inaccessible!');
    $size = filesize($file);
    $name = rawurldecode($name);
    $known_mime_types=array(
        "htm" => "text/html",
        "exe" => "application/octet-stream",
        "zip" => "application/zip",
        "doc" => "application/msword",
        "jpg" => "image/jpg",
        "php" => "text/plain",
        "xls" => "application/vnd.ms-excel",
        "ppt" => "application/vnd.ms-powerpoint",
        "gif" => "image/gif",
        "pdf" => "application/pdf",
        "txt" => "text/plain",
        "html"=> "text/html",
        "png" => "image/png",
        "jpeg"=> "image/jpg"
    );

    if($mime_type==''){
        $file_extension = strtolower(substr(strrchr($file,"."),1));
        if(array_key_exists($file_extension, $known_mime_types)){
            $mime_type=$known_mime_types[$file_extension];
        } else {
            $mime_type="application/force-download";
        };
    };
    @ob_end_clean();
    if(ini_get('zlib.output_compression'))
    ini_set('zlib.output_compression', 'Off');
    header('Content-Type: ' . $mime_type);
    header('Content-Disposition: attachment; filename="'.$name.'"');
    header("Content-Transfer-Encoding: binary");
    header('Accept-Ranges: bytes');

    if(isset($_SERVER['HTTP_RANGE']))
    {
        list($a, $range) = explode("=",$_SERVER['HTTP_RANGE'],2);
        list($range) = explode(",",$range,2);
        list($range, $range_end) = explode("-", $range);
        $range=intval($range);
        if(!$range_end) {
            $range_end=$size-1;
        } else {
            $range_end=intval($range_end);
        }

        $new_length = $range_end-$range+1;
        header("HTTP/1.1 206 Partial Content");
        header("Content-Length: $new_length");
        header("Content-Range: bytes $range-$range_end/$size");
    } else {
        $new_length=$size;
        header("Content-Length: ".$size);
    }

    $chunksize = 1*(1024*1024);
    $bytes_send = 0;
    if ($file = fopen($file, 'r'))
    {
        if(isset($_SERVER['HTTP_RANGE']))
        fseek($file, $range);

        while(!feof($file) &&
            (!connection_aborted()) &&
            ($bytes_send<$new_length)
        )
        {
            $buffer = fread($file, $chunksize);
            echo($buffer);
            flush();
            $bytes_send += strlen($buffer);
        }
        fclose($file);
    } else
        die('Error - can not open file.');
    die();
}
set_time_limit(0);

/*set your folder*/
$file_path='uploads/'."your file";

/*output must be folder/yourfile*/

output_file($file_path, ''."your file".'', $row['type']);

/*back to index.php while downloading*/
header('Location:index.php');
?>
hemnath mouli
  • 2,617
  • 2
  • 17
  • 35
jundell agbo
  • 269
  • 3
  • 2
  • 2
    Where did you get this from? It seems powerful – Axel A. García May 07 '16 at 04:31
  • @jundell-agbo interesting and for a crt file? – fralbo Oct 11 '16 at 17:40
  • This is working for a very big file also. Great solution. But` $chunksize = 1*(1024*1024);` is slow. I tried with multiple values and noticed that ` $chunksize = 8*(1024*1024);` is using all the available bandwidth. – Linga Jun 19 '18 at 12:20
18

In case you have to download a file with a size larger than the allowed memory limit (memory_limit ini setting), which would cause the PHP Fatal error: Allowed memory size of 5242880 bytes exhausted error, you can do this:

// File to download.
$file = '/path/to/file';

// Maximum size of chunks (in bytes).
$maxRead = 1 * 1024 * 1024; // 1MB

// Give a nice name to your download.
$fileName = 'download_file.txt';

// Open a file in read mode.
$fh = fopen($file, 'r');

// These headers will force download on browser,
// and set the custom file name for the download, respectively.
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $fileName . '"');

// Run this until we have read the whole file.
// feof (eof means "end of file") returns `true` when the handler
// has reached the end of file.
while (!feof($fh)) {
    // Read and output the next chunk.
    echo fread($fh, $maxRead);

    // Flush the output buffer to free memory.
    ob_flush();
}

// Exit to make sure not to output anything else.
exit;
Parziphal
  • 6,222
  • 4
  • 34
  • 36
  • I just tried this and it killed my server. Wrote a massive number of errors to my logs. – Daniel Williams Aug 09 '17 at 02:21
  • It would be useful to know what the logs were about. – Parziphal Aug 09 '17 at 04:13
  • Yeah sorry, the log file got so big I had to just nuke it, so I didn't get to see. – Daniel Williams Aug 09 '17 at 04:14
  • I was having to set up something like this on a server that I had very limited access to. My download script kept redirecting to the home page and I couldn't figure out why. Now I know the issue was a memory error and this code solved it. – Gavin Feb 21 '18 at 13:57
  • If you just use `ob_flush()` there might be the error: **ob_flush(): failed to flush buffer. No buffer to flush**. wrap around it with `if (ob_get_level() > 0) {ob_flush();}` (Reference https://stackoverflow.com/a/9182133/128761 ) – vee Dec 18 '18 at 03:08
  • Add `fclose($fh);` at the end before exit. Add `header('Content-Length: ' . filesize($file));` to let user know file size. +1 your answer :) – vee Dec 18 '18 at 03:34
11

A modification of the accepted answer above, which also detects the MIME type in runtime:

$finfo = finfo_open(FILEINFO_MIME_TYPE);
header('Content-Type: '.finfo_file($finfo, $path));

$finfo = finfo_open(FILEINFO_MIME_ENCODING);
header('Content-Transfer-Encoding: '.finfo_file($finfo, $path)); 

header('Content-disposition: attachment; filename="'.basename($path).'"'); 
readfile($path); // do the double-download-dance (dirty but worky)
Jure Sah
  • 159
  • 2
  • 4
6

You can stream download too which will consume significantly less resource. example:

$readableStream = fopen('test.zip', 'rb');
$writableStream = fopen('php://output', 'wb');

header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="test.zip"');
stream_copy_to_stream($readableStream, $writableStream);
ob_flush();
flush();

In the above example, I am downloading a test.zip (which was actually the android studio zip on my local machine). php://output is a write-only stream (generally used by echo or print). after that, you just need to set the required headers and call stream_copy_to_stream(source, destination). stream_copy_to_stream() method acts as a pipe which takes the input from the source stream (read stream) and pipes it to the destination stream (write stream) and it also avoids the issue of allowed memory exhausted so you can actually download files that are bigger than your PHP memory_limit.

Saud Qureshi
  • 1,456
  • 1
  • 19
  • 20
  • What do you mean by the download is streamed? – Parsa Yazdani Jun 21 '19 at 23:06
  • 1
    @ParsaYazdani It means the downloaded data will be chunked. Please look onto the concept of streaming for more details. Note: this is not the only to stream (chunk) download the file in PHP. But it surely is one of the easiest methods. – Saud Qureshi Jun 22 '19 at 12:03
5

The answers above me works. But, I'd like to contribute a method on how to perform it using GET

on your html/php page

$File = 'some/dir/file.jpg';
<a href="<?php echo '../sumdir/download.php?f='.$File; ?>" target="_blank">Download</a>

and download.php contains

$file = $_GET['f']; 

header("Expires: 0");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

$ext = pathinfo($file, PATHINFO_EXTENSION);
$basename = pathinfo($file, PATHINFO_BASENAME);

header("Content-type: application/".$ext);
header('Content-length: '.filesize($file));
header("Content-Disposition: attachment; filename=\"$basename\"");
ob_clean(); 
flush();
readfile($file);
exit;

this should work on any file types. this is not tested using POST, but it could work.

Mo Chan
  • 187
  • 2
  • 8
5

you can use download attribute to force download a file:

<a href="https://test.com/aaa.exe" download>click here to download</a>
علیرضا
  • 2,434
  • 1
  • 27
  • 33
4

The following code is a correct way of implementing a download service in php as explained in the following tutorial

header('Content-Type: application/zip');
header("Content-Disposition: attachment; filename=\"$file_name\"");
set_time_limit(0);
$file = @fopen($filePath, "rb");
while(!feof($file)) {
    print(@fread($file, 1024*8));
    ob_flush();
    flush();
}
Grigor Nazaryan
  • 567
  • 5
  • 18
  • 2
    You have two variables in this code: `file_name` and `filePath`. Not very good coding practice. Especially without explanation. Linking to external tutorial not helpful. – Khom Nazid May 12 '19 at 13:19
2

try this:

header('Content-type: audio/mp3'); 
header('Content-disposition: attachment; 
filename=“'.$trackname'”');                             
readfile('folder name /'.$trackname);          
exit();
Zevan
  • 10,097
  • 3
  • 31
  • 48
nqobile
  • 29
  • 1
2

http://php.net/manual/en/function.readfile.php

That's all you need. "Monkey.gif" change to your file name. If you need to download from other server, "monkey.gif" change to "http://www.exsample.com/go.exe"

Assasin
  • 21
  • 1
  • 2
    Welcome to StackOverflow. It's always advisable to include the code directly instead of adding a link to avoid the link issues. – Stranger Nov 26 '17 at 11:41