利用PHP实现智能文件类型检测的实现代码
使用文件后缀和MIME类型检测
通常我们想严格限制文件类型的时候,可以简单地用$_FILES['myFile']['type'] 取得文件的 MIME类型然后来检测它是否是合法的类型。
或者我们可以取文件名的最后几个字符来获取文件后缀,不幸的是,这些方法并不足够,可以很容易地改变文件的扩展名绕过这个限制。此外,MIME类型信息是由浏览器发送的,而且,对于大多数浏览器,即使不是全部,是根据文件的扩展名的来给出MIME类型信息的!因此,MIME类型,就像扩展名一样,可以很容易地欺骗。
使用“魔术字节”
确定文件类型的最佳方法是通过检查文件的前几个字节 – 称为“魔字节”。魔术字节本质上是文件头中不同长度在2到40个字节之间的,或在文件末尾的签名。有上百个类型的文件,他们中相当多的文件类型有好几个文件签名与它们相关联。在这里你可以看到一个文件签名列表。
偷懒的办法是使用fileinfo扩展,PHP 5.3.0 默认是启用的(根据官方MANUAL),如果没有启用,你可以自己启用
如在windows下面:
复制代码 代码如下:
extension=php_fileinfo.dll
linux下面:
复制代码 代码如下:
extension=fileinfo.so
#如不能正常工作,再加上下面这条
#mime_magic.magicfile=/usr/share/file/magic
windows下面如不能正常工作:
可参考:http://www.php.net/manual/en/fileinfo.installation.php#82570
下载file-5.03-bin.zip ,解压出来,在其中的share目录有magic.mgc 、magic 两个文件。
然后添加一个名为MAGIC的系统环境变量指向magic 文件。如D:\software\PHP\extras\misc\magic
复制代码 代码如下:
function getFileMimeType($file) {
$buffer = file_get_contents($file);
$finfo = new finfo(FILEINFO_MIME_TYPE);
return $finfo->buffer($buffer);
}
$mime_type = getFileMimeType($file);
switch($mime_type) {
case "image/jpeg":
// your actions go here...
}
处理图像上传
如果你打算只允许图像上传,那么你可以使用内置的getimagesize()函数,以确保用户实际上是上传一个有效的图像文件。如果该文件不是有效的图像文件,这个函数返回false。
复制代码 代码如下:
// 假设file input 域的name 属性为myfile
$tempFile = $_FILES['myFile']['tmp_name']; // path of the temp file created by PHP during upload
$imginfo_array = getimagesize($tempFile); // returns a false if not a valid image file
if ($imginfo_array !== false) {
$mime_type = $imginfo_array['mime'];
switch($mime_type) {
case "image/jpeg":
// your actions go here...
}
}
else {
echo "This is not a valid image file";
}
手动读取和解释“魔法字节”
如果由于某种原因,你不能安装FileInfo扩展,那么你仍然可以手动确定,通过读取文件的前几个字节,并比较它们与已知的魔法与特定文件类型相关联的字节的文件类型。这个过程肯定少许的试验和错误,因为还有一种可能,有少数非法的魔法字节与合法文件格式关联了。
然而这不是不可能的,几年前,我被要求做一个只允许真正的 mp3 文件上传的脚本文件,并且,当时我们不能用 Fileinfo, 我们只能依靠这种手动检测的方式了.
我花了一段时间来解析一些mp3文件的非法魔法字节,但很快,我得到了一个稳定的上传脚本。
在本文结束前,我想给大家一个警告: 确保你永远没有调用一个 include() 来包含一个上传的文件,因为PHP代码很可能会巧妙地隐藏在图片里面,并且图片也可以成功的通过你的文件检测,当这样的脚本运行时,只可能给系统带来破坏。
译自:http://designshack.co.uk/articles/php-articles/smart-file-type-detection-using-php/

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
