简体   繁体   English

PHP in_array,如果检查不起作用

[英]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. 我似乎无法找出为什么if标记在数组中时会运行。

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. 当脚本读取$ type和$ avatarformats时,它是=到以下内容。

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

$type = .png

The if tag runs when it should not because .png is in the array. if标记在不应该运行时会运行,因为.png在数组中。 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. 我不确定您如何确定类型,但是通常$_FILES['type']是内容类型(例如'image/jpeg' ),而不是文件名本身的扩展名。

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 注意:使用exif_imagetype(),请阅读http://www.php.net/manual/zh/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. 我怀疑in_array()返回的是true,因为语句!in_array($type, $avatarformats)由于句号而评估为true。 It is evaluating the value of $type as an integer because of the decimal place. 由于小数点后的位,它会将$type的值评估为整数。

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个选择:1)首先尝试从文件扩展名中删除点(即“ .png”至“ png”),然后再将其添加到数组中,然后进行测试。 2) or change your conditional to the following: else if (in_array($type, $avatarformats) == false) { 2)或将您的条件更改为以下内容: else if (in_array($type, $avatarformats) == false) {

in_array() is a strange beast and I try to avoid it at the best of times. in_array()是一种奇怪的野兽,我会尽量避免使用它。 isset() is your friend and much faster than in_array under most conditions anyways. 在大多数情况下,isset()是您的朋友,并且比in_array快得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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