Ali
Ali

Reputation: 267049

Displaying images using PHP not working

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?

Upvotes: 0

Views: 12267

Answers (3)

deffrin joseph
deffrin joseph

Reputation: 151

<?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.

Upvotes: 4

Ali
Ali

Reputation: 267049

I found the answer, i had some extra whitespace after the ?> tag which was causing the header to not work. grrrrrrr

Upvotes: 2

Matt
Matt

Reputation: 57

Striving for simplicity...

<?php
header('Content-type:' . mime_content_type($file));
readfile($file);

should function as expected.

Upvotes: 2

Related Questions