1

I have some images without extension in their name. Now, when I want to open them some browsers can't detect data as image and show up the binary text.

What is the right script (php) which will take the address of such image, detect it's format and set right headers with image output?

1
  • why not just set the Content-Type header to image/* `? Commented May 19, 2011 at 11:50

4 Answers 4

3

You can use the exif_imagetype function to properly detect what type of image it is, then the image_type_to_mime_type function to get the mime type you want:

header("Content-type: " . image_type_to_mime_type(exif_imagetype("image.jpg")));

You'll need exif support builtin though. I recommend this because it actually checks the signature of the file versus blindly assuming the mime type based on extension. However, if this isn't an option, you'll have to fallback to fileinfo as others have mentioned.

Sign up to request clarification or add additional context in comments.

2 Comments

Since we do not know the file extension we could use PEAR ImageMagick: php.net/manual/en/function.imagick-identifyimage.php
@Mathew You don't have to know the extension of the file. As I mentioned exif_imagetype checks the binary signature, not the extension.
1

You should check fileinfo() http://www.php.net/manual/en/function.finfo-file.php Fileinfo detects the filetype and depending on that u can set your header.

Comments

0

You could use this :

<?php $filename = 'http://static.php.net/www.php.net/images/php.gif'; $file = fopen($filename, 'rb'); $size = getimagesize($file); switch ($size['mime']) { case "IMAGETYPE_GIF": echo "<strong class="highlight">Image</strong> is a gif"; break; case "IMAGETYPE_JPEG": echo "<strong class="highlight">Image</strong> is a jpeg"; break; case "IMAGETYPE_PNG": echo "<strong class="highlight">Image</strong> is a png"; break; } ?>

Comments

0

You could use finfo_file() to determine the MIME type of the file in question and then send a Content-Type header with that information in.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.