Laravel 检查图像路径字符串是否为图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33283993/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 12:33:40  来源:igfitidea点击:

Laravel check if image path string is image

phplaravel

提问by dansan

I'm passing an image path as a GET paremeter when a link is clicked, but I need to check if this is an image for security reasons.

单击链接时,我将图像路径作为 GET 参数传递,但出于安全原因,我需要检查这是否是图像。

When I try this code, where $fileNameis '15612.jpg':

当我尝试此代码时,$fileName“15612.jpg”在哪里:

$fileName = $_GET['fileName'];

$image = array('file' => File::get('unverified-images/'.$fileName));
$rules = array('file' => 'image');
$validator = Validator::make($image, $rules);

if ($validator->fails()) {
  Session::flash('error', 'Not an image'); 
  return Redirect::to('controlpanel');
}

All .jpg files I have tested give 'Not an image', but when I try with a .txt file it doesn't give an error, why is this? I'm guessing im doing something wrong, as the validator is supposed to fail when it's not an image, right?

我测试过的所有 .jpg 文件都给出“不是图像”,但是当我尝试使用 .txt 文件时,它没有给出错误,这是为什么?我猜我做错了什么,因为验证器应该在它不是图像时失败,对吗?

I know the validator takes Input::file()instead of File::get(), but how can I use that if I'm not using a form?

我知道验证器使用Input::file()代替File::get(),但是如果我不使用表单,我该如何使用它?

回答by craig_h

This may be a case of avoiding the validator, and doing the check yourself, so you could do:

这可能是避免验证器并自己进行检查的情况,因此您可以执行以下操作:

$allowedMimeTypes = ['image/jpeg','image/gif','image/png','image/bmp','image/svg+xml'];
$contentType = mime_content_type('path/to/image');

if(! in_array($contentType, $allowedMimeTypes) ){
  Session::flash('error', 'Not an image'); 
  return Redirect::to('controlpanel');
}

回答by Radames E. Hernandez

Other way to check if it is an image is getting the extension of the filelike this with php explodefunction:

检查它是否是图像的其他方法是使用 php函数获取文件的扩展名explode

PHP:

PHP:

$imageExtensions = ['jpg', 'jpeg', 'gif', 'png', 'bmp', 'svg', 'svgz', 'cgm', 'djv', 'djvu', 'ico', 'ief','jpe', 'pbm', 'pgm', 'pnm', 'ppm', 'ras', 'rgb', 'tif', 'tiff', 'wbmp', 'xbm', 'xpm', 'xwd'];

$explodeImage = explode('.', 'path/image.jpg');
$extension = end($explodeImage);

if(in_array($extension, $imageExtensions))
{
    // Is image
}else
{
    // Is not image 
}

This work for me, regards!

这对我有用,问候!

Here you can find an array of all file extensions: click here

在这里您可以找到所有文件扩展名数组单击此处