PHP

Force Download Image File

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.

4 Comments

  1. is it possible to pass variable in filename

  2. 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. Thank you for this wonderful script man

  4. Lalit

    Thank you so much.Its working for me.

Leave a Reply