Question

I'm processing an image into a thumbnail using PHP, and I'm allowing 3 separate extension types through: .jpg, .jpeg, & .png... the first 2 and the latter have to be processed through different functions, namely createimagefromjpg() and createimagefrompng() respectively.

I'm grabbing the file extension of an image and then using an if statement to check which file type it is so it can be processed correctly:

$extension = pathinfo($filename, PATHINFO_EXTENSION);

// Read source image
if ($extension == ('jpg' || 'jpeg')) {
    $source_image = imagecreatefromjpeg($filename); 
    return '1';
} else if ($extension == 'png') {
    $source_image = imagecreatefrompng($filename);
    return '2';
} else {
    return 'error';
}

jpg & jpeg images are processed correctly as this function returns 1... so everything appears to be good. However, when I pass through a png file, it likewise goes into the first branch and returns '1', even though png != jpeg or jpg. Weird. This error causes my thumbnail to not be generated at all.

It gets even more confusing. If I enable strict comparisons by replacing == with === in the IF statemtn, jpg & jpeg files error out completely indicating that apparently 'jpg' != 'jpg' (even though it does), and likewise with jpeg. PNG files break the script completely.


EDIT: The problem seems not to be my IF statement, but the imagecreatefrompng() function. It works for small images (200x200), but not for larger ones... can anyone explain this?

Was it helpful?

Solution

You are using incorrect syntax for your if statement. Use this:

if ($extension == 'jpg' || $extension == 'jpeg') {

Your example is evaluating ('jpg' || 'jpeg') as a boolean. Since a string evaluates to true in PHP, that statement is always correct.

$extension then gets typecast to a boolean making your statement equivalent to (true == true).

Using the === operator will cause $extension not to be typecast, so it will be ("some string value" === true) which is false.

OTHER TIPS

That is not how you write your condition. You currently have...

$extension == ('jpg' || 'jpeg')

Which is basically the same as...

$extension == TRUE

...which is true, so long as the string isn't empty.

Instead, make the comparisons separately like...

$extension == 'jpg' || $extension == 'jpeg'

Alternatively, you could do...

preg_match("/^jpe?g\z/", $extension);

...or...

in_array($extension, array("jpg", "jpeg"))

etc, but they're (arguably) more difficult to read.

You can try to get the mime-type (png of the file by using or mime_content_type or Fileinfo, i think this option would be more accurate.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top