如何检查在PHP中上传的文件types

我用这个代码来检查图像的types,

$f_type=$_FILES['fupload']['type']; if ($f_type== "image/gif" OR $f_type== "image/png" OR $f_type== "image/jpeg" OR $f_type== "image/JPEG" OR $f_type== "image/PNG" OR $f_type== "image/GIF") { $error=False; } else { $error=True; } 

但一些用户抱怨说,他们上传任何types的图像时出现错误,而另一些用户则没有任何错误!

我想知道这是否解决了这个问题:

if (mime_content_type($_FILES['fupload']['type']) == "image/gif"){...

任何意见?

切勿使用$_FILES..['type'] 。 其中包含的信息根本没有validation,这是一个用户定义的值。 自己testingtypes。 对于图片, exif_imagetype通常是一个不错的select:

 $allowedTypes = array(IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF); $detectedType = exif_imagetype($_FILES['fupload']['tmp_name']); $error = !in_array($detectedType, $allowedTypes); 

另外,如果你的服务器支持finfo函数 ,那么finfo函数是很好的。

除了@deceze,你也可以finfo()来检查非图像文件的MIMEtypes:

 $finfo = new finfo(); $fileMimeType = $finfo->file($path . $filename, FILEINFO_MIME_TYPE); 

在我看来,最好的方法是首先使用getimagesize(),然后使用imagecreatefromstring() 。

  $size = getimagesize($filename); if ($size === false) { throw new Exception("{$filename}: Invalid image."); } if ($size[0] > 2500 || $size[1] > 2500) { throw new Exception("{$filename}: Image too large."); } if (!$img = @imagecreatefromstring(file_get_contents($filename))) { throw new Exception("{$filename}: Invalid image content."); } 

通过getimagesize()检查可以防止一些DoS攻击,因为我们不必尝试从用户提供的每个文件(无论是非映像文件还是文件太大imagecreatefromstring()都对imagecreatefromstring()进行映射。 不幸的是,根据PHP文档不能依靠检查图像types的内容。

imagecreatefromstring()最终试图打开文件作为图像 – 如果成功 – 我们有一个图像。

在PHP 5.5中,我使用这个函数获取文件types,并检查图像:

 function getFileType( $file ) { return image_type_to_mime_type( exif_imagetype( $file ) ); } // Get file type $file_type = getFileType( 'path/tohttp://img.dovov.comtest.png' ); echo $file_type; // Prints image/png // 1. All images have mime type starting with "image" // 2. No other non-image mime types contain string "image" in it 

那么你可以这样做:

 if ( strpos( $filetype, 'image' ) !== false ) { // This is an image } 

完整的MIMEtypes列表: http : //www.sitepoint.com/web-foundations/mime-types-complete-list/

当然,你可以检查一下,如果这是一个exif图像,但更好的方式,我认为是这样做的finfo:

 $allowed_types = array ( 'application/pdf', 'image/jpeg', 'image/png' ); $fileInfo = finfo_open(FILEINFO_MIME_TYPE); $detected_type = finfo_file( $fileInfo, $_FILES['datei']['tmp_name'] ); if ( !in_array($detected_type, $allowed_types) ) { die ( 'Please upload a pdf or an image ' ); } finfo_close( $fileInfo ); 

这是我经常使用的简单的一行脚本。

 $image = "/var/www/Core/temp/image.jpg"; $isImage = explode("/", mime_content_type())[0] == "image"; 

基本上我使用mime_content_type()来获取类似“image / jpg”的内容,然后用“/”对其进行爆炸,然后检查数组的第一个元素以查看是否显示“image”。

我希望它的作品!

警告 :以下答案实际上不检查文件types。 它只检查名称。 它不适合实际的安全目的。

编辑:不要使用这种方法,因为它没有安全检查。 我在这里留下这个答案,以便没有人通过尝试这样做像我一样的错误。


我试了下面,它为我工作:

 $allowed = array('gif','png' ,'jpg', 'pdf'); $filename = $_FILES['input_tag_name']['name']; $ext = pathinfo($filename, PATHINFO_EXTENSION); if(!in_array($ext,$allowed) ) { echo 'error'; } 

来源链接