Force Download File Using PHP

Force Download File Using PHP

Here we show you how to force download any types of file like text, image, document, pdf, zip, etc from directory or server in PHP. we need to force the browser to download file other than display. Using header() and readfile() function, you can easily download a file in PHP. We will provide the example of PHP code to force download file in PHP. Also, this simple PHP script helps to implement a download link which downloads a file from the directory. Download a File in PHP
				
					<?php
  
  $fileName = basename('inflay.txt'); // basename() returns the filename from a path
  $filePath = 'mix_files/'.$fileName;
  if(!empty($fileName) && file_exists($filePath))
  {
      
      # Define headers
      header("Cache-Control: public");
      header("Content-Description: File Transfer");
      header("Content-Disposition: attachment; filename=$fileName");
      header("Content-Type: application/zip");
      header("Content-Transfer-Encoding: binary");
      
      # ob_clean() function deletes all of the contents of the topmost output buffer, preventing them from getting sent to the browser.
      ob_clean();
      
      # flush() function requests the server to send its currently buffered output to the browser.
      flush();
      
      # readfile() Read the file
      readfile($filePath); 
      
      exit;
  }
  else
  {
      echo 'The file does not exist.';
  }
?>
				
			

Download a File By Anchor Link

Sometimes we need to provide a link to user for download file from the server. Below sample code to display an HTML link to download a file from the directory using PHP.
HTML:

				
					<a href="download_file.php?file=inflay.pdf">Dowload File</a>

				
			

PHP Code

				
					<?php
  if(!empty($_GET['file']))
  {
      $fileName = basename($_GET['file']); // basename() returns the filename from a path
      $filePath = 'mix_files/'.$fileName;
      if(!empty($fileName) && file_exists($filePath))
      {
          // Define headers
          header("Cache-Control: public");
          header("Content-Description: File Transfer");
          header("Content-Disposition: attachment; filename=$fileName");
          header("Content-Type: application/zip");
          header("Content-Transfer-Encoding: binary");
          # ob_clean() function deletes all of the contents of the topmost output buffer, preventing them from getting sent to the browser.
          ob_clean();
          
          # flush() function requests the server to send its currently buffered output to the browser.
          flush();
          
          # readfile() Read the file
          readfile($filePath);
          exit;
      }
      else
    {
          echo 'The file does not exist.';
      }
  }
?>
				
			

I hope this article helps you.
Thanks for visiting Inflay.com .