Showing posts with label Force directly linked file to download. Show all posts
Showing posts with label Force directly linked file to download. Show all posts

Friday, October 18, 2013

Force directly linked file to download

Is there any way to provide a direct link to a file & force the browser to download it using PHP?

E.g http://www.website.com/directory/file.jpg

We’re dealing with huge files here & Chrome in particular seems to have a problem rendering the image, so all the user sees is a blank screen when visiting the file directly. Even though they can still right-click in the blank screen & download the file it’s confusing.

We used to output the files from PHP yet we ran into memory problems so switched to providing a direct link instead. The files go up to approximately 5GB, they aren’t all images. We have zips, PDFs, PSDs etc.

Currently, the file is requested through a PHP script which accepts the ID of the file & obtain its URL. The PHP script then redirects to the user to full URL of the file.

How can we ensure that downloads are forced & we don’t run into memory issues with the larger files?

Thank you

Just use X-Sendfile yet you need to configure it first … using XSendFilePath

if (file_exists($file)) {    header("X-Sendfile: $file");    header("Content-Type: application/octet-stream");    header(sprintf("Content-Disposition: attachment; filename=\"%s\"", basename($file)));    exit();}

Note* Please ensure $file is properly escaped before you verify & serve the file

XSendFilePath only works on Apache for other servers please see : Caching HTTP responses when they are dynamically created by PHP