Output an Image in PHP

前端 未结 12 1219
萌比男神i
萌比男神i 2020-11-22 14:33

I have an image $file ( eg ../image.jpg )

which has a mime type $type

How can I output it to the browser?

12条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 15:06

    $file = '../image.jpg';
    
    if (file_exists($file))
    {
        $size = getimagesize($file);
    
        $fp = fopen($file, 'rb');
    
        if ($size and $fp)
        {
            // Optional never cache
        //  header('Cache-Control: no-cache, no-store, max-age=0, must-revalidate');
        //  header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        //  header('Pragma: no-cache');
    
            // Optional cache if not changed
        //  header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($file)).' GMT');
    
            // Optional send not modified
        //  if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) and 
        //      filemtime($file) == strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']))
        //  {
        //      header('HTTP/1.1 304 Not Modified');
        //  }
    
            header('Content-Type: '.$size['mime']);
            header('Content-Length: '.filesize($file));
    
            fpassthru($fp);
    
            exit;
        }
    }
    

    http://php.net/manual/en/function.fpassthru.php

提交回复
热议问题