Force Download Image File

November 28, 2007 | PHP

This script is useful when we want to download an image file (JPG, PNG, GIF) instead of preview it into our browser. A download dialog will appear and the image will not be displayed.

< ?php
// Define the image type. We can remove this but not recommended
header("Content-type: image/jpeg");

// Define the name of image after downloaded
header('Content-Disposition: attachment; filename="file.jpg"');

// Read the original image file
readfile('file.jpg');
?>

Let’s give it a try. Save the script as download.php and put file file.jpg in the same directory/folder as download.php. Then open download.php using our web browser.

We should now see download dialog instead of file.jpg opened in the browser.

3 comments

This post has 3 comments, great!

  1. nayeem 27/05/2008 at 12:27

    is it possible to pass variable in filename

  2. articles directory 10/08/2009 at 12:28

    It is not working ..
    Try this

    $file = “misc_tasks.txt”

    // Quick check to verify that the file exists
    if( !file_exists($file) ) die(“File not found”);

    // Force the download
    header(“Content-Disposition: attachment; filename=\”" . basename($file) . “\”");
    header(“Content-Length: ” . filesize($file));
    header(“Content-Type: application/octet-stream;”);
    readfile($file);

  3. Pico RG 18/09/2010 at 15:05

    Thank you for this wonderful script man

 

Leave a comment

Allowed tags are: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>


 



Switch to our mobile site