Question

I post an image url to a php script. In this php script I get the image url and check what the extension is and if this extension matches a couple of extensions or not:

        $ext1 = pathinfo($_POST['form_pic'], PATHINFO_EXTENSION);
        $ext = strtolower($ext1);

        if($ext != 'jpg' || $ext != 'jpeg' || $ext != 'png' || $ext != 'gif') {
            echo $ext; echo "wrong";        
        }else{
            echo "a correct extension";
        }

But even when I a post an url like: http://www.test.com/picture.jpg and he gets the extension, in this case jpg, he still goes through the if statement, saying the extension is not equal to the one mentioned in the if statement.

I don't know what I am doing wrong?

Was it helpful?

Solution

Your code is almost right but you have to use correct operator which is && in this case.

Please try this:

$ext1 = pathinfo($_POST['form_pic'], PATHINFO_EXTENSION);
$ext = strtolower($ext1);

   if($ext != 'jpg' && $ext != 'jpeg' && $ext != 'png' && $ext != 'gif') {
        echo $ext; echo "wrong";        
   } else {
        echo "A correct extension";
   }

When you a use a sequence of negative statements there always should be used operator &&.

There are a lot of ways to do what you want but if you want to keep your code as it is just change || to && and you will be fine.

Please read more about Logical Operators in PHP.

OTHER TIPS

You want to use and in this logic, not or.

if($ext != 'jpg' && $ext != 'jpeg' && $ext != 'png' && $ext != 'gif')

Currently, your if statement reads "If the extension isn't jpg or isn't png or isn't gif", which will always match, even if the extension is permitted (i.e. "jpg"), because "jpg" != "png".

You want and because it'll make the if statement read "If the extension isn't jpg and isn't png and isn't gif", then it's invalid.

You could also do

if(in_array($ext,array('gif','jpg','jpeg','png')){
//good
}else{
//bad
}

Try switching the logic:

if($ext == 'jpg' || $ext == 'jpeg' || $ext == 'png' || $ext == 'gif') {
    echo "a correct extension";
}else{
    echo $ext; echo "wrong";        
}

Using OR, the condition will be triggered if any of the criteria are met, and since a .jpg extension won't match a .png one, it'll give you the Wrong message.

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