How to make a file downloadable in PHP?

Send file with HTTPRange support (partial download):

function smartReadFile($location, $filename, $mimeType='application/octet-stream')
{ if(!file_exists($location))
  { header ("HTTP/1.0 404 Not Found");
    return;
  }

  $size=filesize($location);
  $time=date('r',filemtime($location));

  $fm=@fopen($location,'rb');
  if(!$fm)
  { header ("HTTP/1.0 505 Internal server error");
    return;
  }

  $begin=0;
  $end=$size;

  if(isset($_SERVER['HTTP_RANGE']))
  { if(preg_match('/bytes=\h*(\d+)-(\d*)[\D.*]?/i', $_SERVER['HTTP_RANGE'], $matches))
    { $begin=intval($matches[0]);
      if(!empty($matches[1]))
        $end=intval($matches[1]);
    }
  }

  if($begin>0||$end<$size)
    header('HTTP/1.0 206 Partial Content');
  else
    header('HTTP/1.0 200 OK');

  header("Content-Type: $mimeType");
  header('Cache-Control: public, must-revalidate, max-age=0');
  header('Pragma: no-cache');
  header('Accept-Ranges: bytes');
  header('Content-Length:'.($end-$begin));
  header("Content-Range: bytes $begin-$end/$size");
  header("Content-Disposition: inline; filename=$filename");
  header("Content-Transfer-Encoding: binary\n");
  header("Last-Modified: $time");
  header('Connection: close');

  $cur=$begin;
  fseek($fm,$begin,0);

  while(!feof($fm)&&$cur<$end&&(connection_status()==0))
  { print fread($fm,min(1024*16,$end-$cur));
    $cur+=1024*16;
  }
}
?>

function smartReadFile($location, $filename, $mimeType='application/octet-stream')
{ if(!file_exists($location))
  { header ("HTTP/1.0 404 Not Found");
    return;
  }
0

function smartReadFile($location, $filename, $mimeType='application/octet-stream')
{ if(!file_exists($location))
  { header ("HTTP/1.0 404 Not Found");
    return;
  }
1

function smartReadFile($location, $filename, $mimeType='application/octet-stream')
{ if(!file_exists($location))
  { header ("HTTP/1.0 404 Not Found");
    return;
  }
2

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|false

Code language: PHP (php)

The readfile() function has the following parameters:

  • $filename is the path to the file.
  • $use_include_path if set to true, the function will search for the file in the include path.
  • <?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)
    0 specifies the stream context.

The readfile() function returns the number of bytes if it successfully reads data from the file, or

<?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)
2 if it fails to read.

PHP download file example

The following example shows how to download the

<?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)
3 file using the readfile() function example.

How to force a file to download in PHP?

Forcing a file to download using PHP: We will be using PHP here as the server-side scripting language. In PHP, this can be done by using readfile() function. The main function of readfile() is to output a file. On clicking any of the hyperlinks the respective file will be downloaded by the browser as shown.

How to create a download button in PHP?

The idea is to make a download button which will redirect you to another page with the PHP script that will automatically start the download..
Creating a download button:.
Output:.
Output:.
PHP code to download: When the user clicks the above button, the code will be redirected to the “downloadFile. php” file..

How to download a file from URL in PHP?

Steps to download the file:.
Initialize a file URL to the variable..
Create cURL session..
Declare a variable and store the directory name where the downloaded file will save..
Use the basename() function to return the file basename if the file path is provided as a parameter..
Save the file to the given location..

How to download the PDF file in PHP?

Below example to illustrate concept of downloading PDF file using HTML link..
Here downloading file appears to be PDF format but without any content which shows error on opening in any application..
HTML code: <! DOCTYPE html> < html > < head > ... .
PHP code: <? php. $file = $_GET [ "file" ] . ". pdf" ; ... .
Output:.