PHP Download File

PHP allows us to download a file easily using built-in readfile() function. The readfile() function reads a file and writes it to the output buffer.

readfile() - Outputs a file

int readfile (string $filename, string $mode [, bool $use_include_path = FALSE [,  resource $context ]] )  

Reads a file and writes it to the output buffer.

Parametes:

filename: The filename being read.

use_include_path: You can use the optional second parameter and set it to TRUE, if you want to search for the file in the include_path, too.

context: A context stream resource.

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.

PHP Download File Example: Text File

File: download.php

<?php 
  $file_url = "https://nexladder.com/resource.txt";
  header('Content-Type: application/octet-stream');
  header('Content-Transfer-Encoding: utf-8');
  header("Content-disposition: attachment; filename="" . basename($file_url) . """);
  readfile($file_url);
?>