Search code examples
phppathinfo

Image url can't get through if statement


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?


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.