Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Automatically Start a Download in PHP?

What code do you need to add in PHP to automatically have the browser download a file to the local machine when a link is visited?

I am specifically thinking of functionality similar to that of download sites that prompt the user to save a file to disk once you click on the name of the software?

like image 467
kaybenleroll Avatar asked Sep 03 '08 00:09

kaybenleroll


People also ask

How can I download image from PHP code?

You can force images or other kind of files to download directly to the user's hard drive using the PHP readfile() function. Here we're going to create a simple image gallery that allows users to download the image files from the browser with a single mouse click. Let's create a file named "image-gallery.


1 Answers

Send the following headers before outputting the file:

header("Content-Disposition: attachment; filename=\"" . basename($File) . "\""); header("Content-Type: application/octet-stream"); header("Content-Length: " . filesize($File)); header("Connection: close"); 

@grom: Interesting about the 'application/octet-stream' MIME type. I wasn't aware of that, have always just used 'application/force-download' :)

like image 83
Robert Swisher Avatar answered Oct 10 '22 01:10

Robert Swisher