Search code examples
phpfile-iocontent-type

Extension missing for images rendered via readfile() function on downloading using php


The extensions are missing for images downloaded from a image which is rendered using readfile function.

The getphoto function code looks like this:

    <?php

    header('Content-Description: File Transfer');
    header('Access-Control-Allow-Origin:*');
    header('Cache-Control:public, max-age=864000');
    header('Content-Type:image/jpg');
    header('Expires: access plus 30 days');
    ob_clean();
    flush();
    readfile($filePath);
    ?>

    <img src="http://localhost/prjt/getphoto/ZmLj" />

Solution

  • You need to add a content-disposition header:

       header('Content-Disposition: attachement; ' .
                   ' filename="yourimage.suf"; size="'2311"');
    

    this will tell the browser to open a download dialog with the given filename.

    Next, you won't render an html tag after streaming the data of the image to the client. And, after putting the headers in the buffer, you shouldn't erase them with ob_clean. Full code:

    <?php
    
        ob_clean();
    
        header('Content-Description: File Transfer');
        header('Access-Control-Allow-Origin:*');
        header('Cache-Control:public, max-age=864000');
        header('Content-Type:image/jpg');
        header('Expires: access plus 30 days');
        header('Content-Disposition: attachement; ' .
                       ' filename="yourimage.suf"; size="'2311"');
    
        readfile($filePath);
    
    ?>
    // EOF !!