PHP Download File PHP

PHP Download File  

PHP Download File

PHP Download File

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


PHP readfile() function

Syntax

  1. int readfile ( string $filename [, bool $use_include_path = false [, resource $context ]] )  

$filename: represents the file name

$use_include_path: it is the optional parameter. It is by default false. You can set it to true to the search the file in the included_path.

$context: represents the context stream resource.

int: it returns the number of bytes read from the file.


 

PHP Download File Example: Text File

File: download1.php

  1. <?php  
  2. $file_url = 'https://www.javatpoint.com/f.txt';  
  3. header('Content-Type: application/octet-stream');  
  4. header("Content-Transfer-Encoding: utf-8");   
  5. header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\"");   
  6. readfile($file_url);  
  7. ?>  

PHP Download File Example: Binary File

File: download2.php

  1. <?php  
  2. $file_url = 'https://www.myremoteserver.com/file.exe';  
  3. header('Content-Type: application/octet-stream');  
  4. header("Content-Transfer-Encoding: Binary");   
  5. header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\"");   
  6. readfile($file_url);  
  7. ?>  

Download free E-book of PHP


#askProgrammers
Learn Programming for Free


Join Programmers Community on Telegram


Talk with Experienced Programmers


Just drop a message, we will solve your queries