![](/img/trans.png)
[英]What's wrong with my use of the LIKE statement with a variable in php
[英]What's wrong with my If-statement to check uploaded file? (PHP)
我正在尝试测试上传的文件是否是我想要的图像类型。 如果不是gif,jpeg,png,则应回显“问题”。 但是,当我执行此代码时,总是表示存在问题。 我的if语句怎么了?
$uploadfile_type=$_FILES['userfile']['type'];
if ( ($uploadfile_type !='image/gif') || ($uploadfile_type !='image/jpeg')
|| ($uploadfile_type !='image/png'))
{
echo 'Problem: file is not a gif or jpeg or png!';
exit;
}
当我仅检查一种类型的图像时,此代码有效。 例如:if($ uploadfile_type!='image / gif')->此语句将起作用,但是当我添加OR时它不会起作用。
应该使用AND( &&
)时使用OR( ||
)。 您想说的不是GIF ,不是JPG ,不是PNG的问题。 使用OR,唯一不会说有问题的方法是,如果您有某种文件设法一次全部为3种类型。
有一个谜语:
我的口袋里有两个硬币。 它们的总价值为三十美分。 其中之一不是镍。 这些是什么?
答案是它们是四分之一,而且是镍-该四分之一满足“其中一个不是镍”的条件。 这是您面临的问题。 每个文件not a gif
或not a jpeg
,甚至不是gif和not a jpeg
。 gif not jpegs
,而jpeg not gifs
。 因此,正如其他人所说,您需要使用AND
而不是OR
。
您应该定义一个可接受的模仿类型列表:
$accepted_types = array(
'image/gif',
'image/jpeg',
'image/png',
);
$uploadfile_type=$_FILES['userfile']['type'];
if (!in_array($uploadfile_type, $accepted_types))
{
echo 'Problem: file is not a gif or jpeg or png!';
exit;
}
我希望这会有所帮助,杰罗姆·瓦格纳
您需要使用AND而不是OR:
if ( ($uploadfile_type !='image/gif') && ($uploadfile_type !='image/jpeg')
&& ($uploadfile_type !='image/png'))
OR总是失败,因为文件只能是单一类型。
乍得的答案是正确的。
如果要缩短代码并使其更美观:
if (!in_array($uploadfile_type, array('image/gif', 'image/jpeg', 'image/png'))
{
// bad
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.