File::extension() 不适用于 if in Laravel

File::extension() doesn't work with if in Laravel

我 运行 遇到了一个奇怪的问题。我正在使用 File::extension($file),实际上得到的答案是 'pdf'。我 var_dump() File::extension($file) 并且它显示具有 3 个字符的字符串的值肯定是 'pdf'。

然后我尝试在 if 语句中比较它,但它进入了 if 语句中不应该的地方。这真是一种奇怪的行为。

$fileType = File::extension($request->frequencyPlan->getClientOriginalName());

if ($fileType != 'pdf' || $fileType != 'doc') {
    return $this->showEstablishmentsEdit('fileTypeErrorForPDF');
};

我是不是漏掉了什么?


P.S:对于那些想知道的人,我无法使用 mimeType 验证器,因为我收到另一个错误

'Unable to guess the mime type as no guessers are available (Did you enable the php_fileinfo extension?)'

而且我认为上面的 if 语句无论如何都应该有效。

试试这个:

$fileType = $request->frequencyPlan->extension();

if ($fileType !== 'pdf' && $fileType !== 'doc') {
  return $this->showEstablishmentsEdit('fileTypeErrorForPDF');
};

以及您的其他问题:

'Unable to guess the mime type as no guessers are available (Did you enable the php_fileinfo extension?)'

托管服务器:

  • 联系托管服务提供商并告诉他启用此扩展程序 php_fileinfo.

本地主机:

  • 你的操作系统是什么?

你的if语句有逻辑错误。

$fileType 等于 pdf 时,您的 if 条件仍将计算为 true$fileType != 'pdf' 将是 false,但后半部分 $fileType != 'doc'true,并且由于您将这些条件组合在一起 "or",结果是 true.

$fileType = 'pdf'.
那么$fileType != 'pdf'就是false.
那么$fileType != 'doc'就是true

因此,($fileType != 'pdf' || $fileType != 'doc') === (false || true) === (true),进入if分支。

我假设如果扩展名不是 "pdf" 并且 不是 "doc",你想进入 if 分支。

您的代码应该是:

if ($fileType != 'pdf' && $fileType != 'doc') {
    return $this->showEstablishmentsEdit('fileTypeErrorForPDF');
};