php file force download

When I use this code to download this image (only used for testing purposes), I open the downloaded image, and all it gives me is an error. i tried it in chrome. opening it with windows photo viewer, it says that it can’t display the picture because it is empty???
here is the code:

 // Define the path to file
 $file = '';

     // File doesn't exist, output error
     die('file not found');
     header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename='.basename($file));
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        header('Content-Length: ' . filesize($file));

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

I’ve had a chance to work it out. Your problem is two-fold.

First, remove the www. from the url.

Second, remove the call to filesize($file) which is throwing an error because PHP doesn’t know the size of the file before it downloads the file. (really, just remove the whole line)

Removing these two things, I was successful.

Solution 2

Replace ob_clean() with ob_end_clean()

You’re still buffering, so none of the image contents get to the browser.

Solution 3

If your intention is just the download the file from a third party on click of a link, you could use the new property download in the anchor tag.

The code will look something like

<a download href="path/to/the/download/file" rel="nofollow noreferrer noopener"> Clicking on this link will force download the file</a>

It works on firefox and chrome latest version. Should I mention that I didn’t check it in IE? 😛

Solution 4




echo file_get_contents($file);

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply