How to Force download a File in PHP (original) (raw)

Skip to content

Summary: in this tutorial, you will learn how to download a file in PHP using the readfile() function.

Introduction to the PHP readfile() function #

The readfile() function reads data from a file and writes it to the output buffer.

Here’s the syntax of the readfile() function:

readfile ( string $filename , bool $use_include_path = false , resource $context = ? ) : int|falseCode language: PHP (php)

The readfile() function has the following parameters:

The readfile() function returns the number of bytes if it successfully reads data from the file, or false if it fails to read.

PHP download file example #

The following example shows how to download the readme.pdf file using the readfile() function example.

`<?php

$filename = 'readme.pdf';

if (file_exists($filename)) { header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename="' . basename($filename) . '"'); header('Expires: 0'); header('Cache-Control: must-revalidate'); header('Pragma: public'); header('Content-Length: ' . filesize($filename)); readfile($filename); exit; }`Code language: HTML, XML (xml)

PHP download file with a download rate limit #

To set a download rate limit, you use the following script:

`<?php

$file_to_download = 'book.pdf'; $client_file = 'mybook.pdf';

$download_rate = 200; // 200Kb/s

$f = null;

try { if (!file_exists($file_to_download)) { throw new Exception('File ' . $file_to_download . ' does not exist'); }

if (!is_file($file_to_download)) {
    throw new Exception('File ' . $file_to_download . ' is not valid');
}

header('Cache-control: private');
header('Content-Type: application/octet-stream');
header('Content-Length: ' . filesize($file_to_download));
header('Content-Disposition: filename=' . $client_file);

// flush the content to the web browser
flush();

f=fopen(f = fopen(f=fopen(file_to_download, 'r');

while (!feof($f)) {
    // send the file part to the web browser
    print fread($f, round($download_rate * 1024));

    // flush the content to the web browser
    flush();

    // sleep one second
    sleep(1);
}

} catch (\Throwable $e) { echo $e->getMessage(); } finally { if ($f) { fclose($f); } } `Code language: HTML, XML (xml)

How it works.

Summary #

Did you find this tutorial useful?