简体   繁体   English

PHP 检查图像 mime 类型

[英]PHP check image mime type

This should be so simple, but I have no idea why this is not working.这应该很简单,但我不知道为什么这不起作用。

I send a URL to my server, and I want to check whether this is an image.我向我的服务器发送了一个 URL,我想检查这是否是一个图像。 Then I want to check whether it's a JPEG or PNG.然后我想检查它是 JPEG 还是 PNG。

if(! $image = @getimagesize( $url ) ) {

    return $this->buildResponse( false, 'No image exists at that location' );
}

So I return some JSON response if it isn't an image.因此,如果它不是图像,我会返回一些 JSON 响应。 This works.这行得通。

I then want to check it's extension.然后我想检查它的扩展名。

if( $image['mime']!= 'image/jpeg' || $image['mime']!= 'image/png') {

    return $this->buildResponse( false, 'File must be of type jpeg or png' );
}

So basically I'm checking whether the mime is equal to either of these, if it isn't then I don't want it.所以基本上我正在检查 mime 是否等于其中任何一个,如果不是那么我不想要它。

Okay that should work, but I always get the File must be of type jpeg or png response back.好的,应该可以,但我总是得到File must be of type jpeg or png响应。

A var_dump($image) :一个var_dump($image)

array(7) {
 [0] 1366
 [1] 854
 [2] 2
 [3] "width="
 ["bits"] 8
 ["channels"] 3
 ["mime"] "image/jpeg"
}

And a var_dump($image['mime']) :还有一个var_dump($image['mime'])

string(10) "image/jpeg"

Am I being stupid, going mad or missing something stupidly obvious here.我是在愚蠢,发疯还是在这里遗漏了一些愚蠢明显的东西。

if( $image['mime'] != 'image/jpeg' || $image['mime'] != 'image/png')

这永远是真的

I understand how this can be a little confusing when you've been struggling on it for a while, so I'll explain the logic behind it. 我了解当您为此苦苦挣扎了一段时间后,这可能会有些混乱,因此,我将解释其背后的逻辑。 You're stating two conditions of which you want one to be satisfied. 您要说明两个要满足的条件。 Yet the if-block triggers an error when either of them doesn't satisfy. 但是,如果其中一个都不满足,则if块会触发错误。 Because the two conditions are mutually exclusive, this is always the case. 因为这两个条件是互斥的,所以总是这样。 Instead you want the if to check whether they both don't satisfy, thus replacing your current OR-operator with an AND-operator. 相反,你想,如果要检查是否他们不能满足,因此有一个与运营商替换当前的或运营商。

Change the or to an and conditional and it will work.将 or 更改为 and 条件,它将起作用。

if( $image['mime']!= 'image/jpeg' && $image['mime']!= 'image/png')

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

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