Displaying images using PHP not working

Ali picture Ali · Feb 17, 2009 · Viewed 11.5k times · Source

I'm trying to display an image using a PHP script. Basically so the php script is passed on the full path to the image, and it then displays that image in the browser. I've checked to make sure the image exists, it is being read correctly, etc, however in the browser i just see the broken image box (e.g the small red cross in IE) if I go there.

My script sends out these headers:

<?php
header('Last-Modified: ' . gmdate('D, d M Y H:i:s T', filemtime($file)));
header('Content-Type: '.$mime);
header('Content-Length: '.filesize($file)."\n\n");
header('Etag: '.md5($file));
echo $file;
die;

$file contains something like '/var/www/htdocs/images/file.jpg' which works. the $mime is 'image/jpeg'.

I have also tried echoing file_get_contents($file) but it didn't work either.

What is the problem, any thoughts?

Answer

deffrin joseph picture deffrin joseph · May 6, 2016
<?php
$filename = basename($file);
$file_extension = strtolower(substr(strrchr($filename,"."),1));
switch( $file_extension ) 
    {
    case "gif": 
        $ctype="image/gif"; 
        break;
    case "png": 
        $ctype="image/png"; 
        break;
    case "jpeg":
    case "jpg": 
        $ctype="image/jpeg"; 
        break;
    default:
    }
ob_clean();  // add this before header
header('Content-type: ' . $ctype);
readFile($file);  
?>

Some time extra space may be produced in any other file.So those extra spaces can be removed by calling ob_clean() before header() is called.