views:

37

answers:

2

I have a website where the public can upload JPEGs.

Someone from the public was uploading an invalid JPEG that was causing the site to crash for them.

PHP said...

imagecreatefromjpeg() [function.imagecreatefromjpeg]: gd-jpeg, libjpeg: recoverable error: Premature end of JPEG file

I wasn't sure how to get around this, so I Googled and found this site. It told me to add...

ini_set('gd.jpeg_ignore_warning', 1);

I added that in my index.php (the bootstrap of my site, where I do other ini_set()).

This didn't seem to fix it.

How can I handle this case of invalid JPEGs? Am I doing something wrong with the INI set? I'm on a shared host so I can't change php.ini directly.

I'm using Kohana 2.3, and its Image library, but I don't think it is really relevant here.

Thanks

+3  A: 

Try sticking an @ character before the command:

$image = @imagecreatefromjpeg("file.jpg");
if(!$image) die("Sorry, bad JPEG");

It's dirty and probably obsolete (not to mention slow), but it'll probably make your code not fail.

Hope this helps!

mattbasta
Oh, I forgot about the error suppressor operator! Thanks, I know its not recommended and ugly as hell, but it *may* be my only hope.
alex
Yep. A quick and dirty fix is often good enough.
Paul McMillan
The `@` is only ugly if failures go completely unchecked and are allowed to propagate. Since you're checking for error conditions on the very next line, this is acceptable usage of `@`.
deceze
@deceze I'm glad the programming gods approve :D
mattbasta
I've been called many things, but "god" is a first... ;D
deceze
+4  A: 

You would usually work with imagecreatefromjpeg like this:

$img = @imagecreatefromjpeg($file);
if (!$img) {
    // handle error yourself
}

Note the @ in front of imagecreatefromjpeg, which is used to suppress errors. Unfortunatly I can't tell you how Kohana does this internally and if it could be persuaded to do the same thing.

deceze
It does the same, just uses a variable function because it supports multiple drivers.
alex