简体   繁体   中英

PHP in_array and if check not working

I've got a script and simple if check to see if a value is in a array. I can't seem to find out why the if tag runs when it's in the array.

else if (!in_array($type, $avatarformats)) {

$error .= '<div class="alert error">You\'re image is not a allowed format</div>';

unlink($_FILES['file']['tmp_name']);

}

When the script reads $type and $avatarformats it's = to the following.

$avatarformats = Array ( [0] => .jpg [1] => .jpeg [2] => .png ) 

$type = .png

The if tag runs when it should not because .png is in the array. Or am I no understaind what am doing.

I'm not sure how you determined the type, but typically the ['type'] that comes from $_FILES is the content type (eg 'image/jpeg' ), rather than the extension of the filename itself.

To test for file extensions, you could use this code:

// get file extension (without leading period)
$ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);

// ...
elseif (!in_array($ext, array('png', 'jpg', 'jpeg'))) {
    // error
}

Note: Use exif_imagetype(), please read http://www.php.net/manual/en/function.exif-imagetype.php

function image_allowed($imgfile) {
  $types = array(IMAGETYPE_JPEG, IMAGETYPE_PNG);
  return in_array(exif_imagetype($imgfile), $types);
}

Then in your code.

else if (!image_allowed($_FILES['file']['tmp_name'])) {

$error .= '<div class="alert error">You\'re image is not a allowed format</div>';

unlink($_FILES['file']['tmp_name']);

}

I suspect that in_array() is returning true because the statement !in_array($type, $avatarformats) is evaluating to true due to the full stop. It is evaluating the value of $type as an integer because of the decimal place.

That being said you have 2 options: 1) Try stripping the dot ie ".png" to "png" from the file extension before adding it to the array in the first place and then do the test. 2) or change your conditional to the following: else if (in_array($type, $avatarformats) == false) {

in_array() is a strange beast and I try to avoid it at the best of times. isset() is your friend and much faster than in_array under most conditions anyways.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM