0

I want to return jpg image on some url in my app (example.com/my/url/to/image).

function footer_image(){

    $name = "/assets/img/mail.jpg";

    header("Content-Type: image/jpg", TRUE);
    header("Content-Length: " . filesize($name));
    echo file_get_contents($name);
}

And I got only broken image :( Tried also this:

   // open the file in a binary mode
$name = "/assets/img/mail.jpg";
$fp = fopen($name, 'rb');

// send the right headers
header("Content-Type: image/jpg");
header("Content-Length: " . filesize($name));

// dump the picture and stop the script
fpassthru($fp);
exit;

When i var_dump $fp I get it's content. Looks like I have bad headers set.

Blejwi
  • 875
  • 1
  • 9
  • 22

2 Answers2

0

Use Content/type: image/jpeg instead of image/jpg

For automation header Content type set you can use this:

$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:
}

header('Content-type: ' . $ctype);

https://stackoverflow.com/a/2634072/4015178

Community
  • 1
  • 1
0

If the image is really the type JPG. Should work with: Content-type: image/jpeg and NOT with Content-type: image/jpg

To automatically check the Content-type, you could use the code below:

function footer_image() {
    $name = "/assets/img/mail.jpg";
    $finfo = finfo_open(FILEINFO_MIME_TYPE); 
    $mime = finfo_file($finfo, $name) ; // return the mimetype 
    header("Content-Type: " . $mime, TRUE);
    header("Content-Length: " . filesize($name));
    echo file_get_contents($name);
}

You could try this in PHP 5.2 or 5.3:

function footer_image() {
    $name = "/assets/img/mail.jpg";
    $mime = mime_content_type($name) ; // php 5.2 and 5.3 = return the mimetype 
    header("Content-Type: " . $mime); // remove the ', true'
    // header("Content-Length: " . filesize($name)); // remove this line to test
    echo file_get_contents($name);
}
Pang
  • 8,605
  • 144
  • 77
  • 113
Allan Andrade
  • 570
  • 8
  • 20