PHP在数组中,如果检查不起作用

PHP在数组中,如果检查不起作用,php,Php,我有一个脚本和简单的if检查,看看数组中是否有值。我似乎无法找到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']); } if标记在不应该运行时运行,因为.png在数

我有一个脚本和简单的if检查,看看数组中是否有值。我似乎无法找到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']);

}

if标记在不应该运行时运行,因为.png在数组中。或者我不知道我在做什么。

我不确定您是如何确定类型的,但通常来自
$\u文件的
['type']
是内容类型(例如
'image/jpeg'
),而不是文件名本身的扩展名

要测试文件扩展名,可以使用以下代码:

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

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

我怀疑数组()中的
返回true,因为语句
!在_array($type,$avatarformats)
中,由于句号,计算结果为true。由于小数点,它将
$type
的值计算为整数

也就是说,您有两种选择: 1) 首先尝试从文件扩展名中删除点,即“.png”到“png”,然后将其添加到数组中,然后进行测试。 2) 或者将您的条件更改为以下内容:
else if(在数组中($type,$avatarformats)==false){

in_array()
是一种奇怪的野兽,我尽量避免在最好的时候使用它。isset()是你的朋友,在大多数情况下都比in_array快得多。

注意:使用exif\u imagetype(),请阅读

然后在你的代码中

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']);

}
else如果(!image\u允许($\u文件['file']['tmp\u名称]])){
$error.='您的图像不是允许的格式';
取消链接($_文件['file']['tmp_名称]]);
}

您可以对这些变量执行
var_dump()
吗?顺便说一句,您不必取消上传文件的链接,PHP会自动完成。在这里工作正常-。我猜(正如杰克所暗示的)您的变量不包含您认为的值。如果.png是字符串,请尝试$type=“.png”@Jack实际上,这取决于临时上传文件的位置。清理不需要的临时文件并没有坏处files@Phil文档说明如果文件未被移动或重命名,则在请求结束时将从临时目录中删除该文件。
否则(在数组中($type,$avatarformats)==false){这似乎是第一次在数组中使用时的技巧。@jack你到底想告诉我什么?运算码不起作用?random neg giver.nice.一些解释会有用的…
在数组中
返回一个布尔值所以
!在数组中()
在数组中()==false
是sameYeah谢谢Phil。奇怪的是,改为==false是如何工作的,尽管嘿;-)@Zappa它显示,给定OP的输入,数组()中的
返回预期结果。
function image_allowed($imgfile) {
  $types = array(IMAGETYPE_JPEG, IMAGETYPE_PNG);
  return in_array(exif_imagetype($imgfile), $types);
}
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']);

}