检查文件是图像还是pdf

问题描述 投票:-5回答:4

我需要在php / laravel中检查文件是图像还是pdf。

这就是我现在拥有的:

return $file['content-type'] == 'image/*';

除了'image / *',我需要添加'application / pdf'

怎么可以添加?

更新

更清楚的是,是否有办法添加更多允许类型而无需执行OR条件。我现在用in_array得到了答案!

php laravel
4个回答
5
投票

我喜欢这种方法,它节省了一些打字

return (in_array($file['content-type'], ['image/jpg', 'application/pdf']));

3
投票

你可以简单地使用OR语句,即

return ($file['content-type'] == 'image/*' || $file['content-type'] == 'application/pdf');

这假设您仍然只想返回true / false。因此调用者将知道该文件是PDF或图像。

或者你的意思是return语句必须产生一个区分这两种类型的值?目前尚不清楚。

如果是后者而不是你想要更像的东西

$type = null;
switch ($file['content-type']) {
  case "image/*":
    $type = "image";
    break;
  case "application/pdf":
    $type = "pdf";
    break;
}
return $type;

1
投票
return $file['content-type'] == 'image/*' || return $file['content-type'] == 'application/pdf';

“||”意思是OR


1
投票

您可以使用OR条件检查文件的内容类型,以添加其他检查条件。

return ($file['content-type'] == 'image/*' || $file['content-type'] == 'application/pdf')

但是如果将所有条件值放在数组中并使用in_array检查它们的存在会更好。

return (in_array(['image/jpg', 'application/pdf'], $file['content-type']));
© www.soinside.com 2019 - 2024. All rights reserved.