PHP

How to Force Download File in PHP


In this article, you will learn how to force download a file in PHP. 

Let’s say you want to download the google icon.

// URL to Google icon
https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_92x30dp.png

Force Download File

In order to force download a file, you can use the readfile() method . Please ensure that fopen_wrappers has been enabled in order to let the readfile() method read a remote URL.

// Name of file
$file_name = 'googlelogo_color_92x30dp.png';

// URL to file
$file_url = 'https://www.google.com/images/branding/googlelogo/2x/' . $file_name;

// Headers
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary"); 
header("Content-disposition: attachment; filename=\"".$file_name."\""); 

// Force download file
readfile($file_url);

// Terminate current script
exit();

Note: The readfile() method functions by reading a file and writing it to the output buffer.


Share on social media

//