Home Backend Development PHP Tutorial 利用PHP实现智能文件类型检测的实现代码_PHP

利用PHP实现智能文件类型检测的实现代码_PHP

Jun 01, 2016 pm 12:15 PM
intelligent

使用文件后缀和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/
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Smart App Control on Windows 11: How to turn it on or off Smart App Control on Windows 11: How to turn it on or off Jun 06, 2023 pm 11:10 PM

Intelligent App Control is a very useful tool in Windows 11 that helps protect your PC from unauthorized apps that can damage your data, such as ransomware or spyware. This article explains what Smart App Control is, how it works, and how to turn it on or off in Windows 11. What is Smart App Control in Windows 11? Smart App Control (SAC) is a new security feature introduced in the Windows 1122H2 update. It works with Microsoft Defender or third-party antivirus software to block potentially unnecessary apps that can slow down your device, display unexpected ads, or perform other unexpected actions. Smart application

The facial features are flying around, opening the mouth, staring, and raising eyebrows, AI can imitate them perfectly, making it impossible to prevent video scams The facial features are flying around, opening the mouth, staring, and raising eyebrows, AI can imitate them perfectly, making it impossible to prevent video scams Dec 14, 2023 pm 11:30 PM

With such a powerful AI imitation ability, it is really impossible to prevent it. It is completely impossible to prevent it. Has the development of AI reached this level now? Your front foot makes your facial features fly, and on your back foot, the exact same expression is reproduced. Staring, raising eyebrows, pouting, no matter how exaggerated the expression is, it is all imitated perfectly. Increase the difficulty, raise the eyebrows higher, open the eyes wider, and even the mouth shape is crooked, and the virtual character avatar can perfectly reproduce the expression. When you adjust the parameters on the left, the virtual avatar on the right will also change its movements accordingly to give a close-up of the mouth and eyes. The imitation cannot be said to be exactly the same, but the expression is exactly the same (far right). The research comes from institutions such as the Technical University of Munich, which proposes GaussianAvatars, which

MotionLM: Language modeling technology for multi-agent motion prediction MotionLM: Language modeling technology for multi-agent motion prediction Oct 13, 2023 pm 12:09 PM

This article is reprinted with permission from the Autonomous Driving Heart public account. Please contact the source for reprinting. Original title: MotionLM: Multi-Agent Motion Forecasting as Language Modeling Paper link: https://arxiv.org/pdf/2309.16534.pdf Author affiliation: Waymo Conference: ICCV2023 Paper idea: For autonomous vehicle safety planning, reliably predict the future behavior of road agents is crucial. This study represents continuous trajectories as sequences of discrete motion tokens and treats multi-agent motion prediction as a language modeling task. The model we propose, MotionLM, has the following advantages: First

Do you know that programmers will be in decline in a few years? Do you know that programmers will be in decline in a few years? Nov 08, 2023 am 11:17 AM

"ComputerWorld" magazine once wrote an article saying that "programming will disappear by 1960" because IBM developed a new language FORTRAN, which allows engineers to write the mathematical formulas they need and then submit them. Give the computer a run, so programming ends. A few years later, we heard a new saying: any business person can use business terms to describe their problems and tell the computer what to do. Using this programming language called COBOL, companies no longer need programmers. . Later, it is said that IBM developed a new programming language called RPG that allows employees to fill in forms and generate reports, so most of the company's programming needs can be completed through it.

An article discussing the application of SLAM technology in autonomous driving An article discussing the application of SLAM technology in autonomous driving Apr 09, 2023 pm 01:11 PM

Positioning occupies an irreplaceable position in autonomous driving, and there is promising development in the future. Currently, positioning in autonomous driving relies on RTK and high-precision maps, which adds a lot of cost and difficulty to the implementation of autonomous driving. Just imagine that when humans drive, they do not need to know their own global high-precision positioning and the detailed surrounding environment. It is enough to have a global navigation path and match the vehicle's position on the path. What is involved here is the SLAM field. key technologies. What is SLAMSLAM (Simultaneous Localization and Mapping), also known as CML (Concurrent Mapping and Localiza

GR-1 Fourier Intelligent Universal Humanoid Robot is about to start pre-sale! GR-1 Fourier Intelligent Universal Humanoid Robot is about to start pre-sale! Sep 27, 2023 pm 08:41 PM

The humanoid robot is 1.65 meters tall, weighs 55 kilograms, and has 44 degrees of freedom in its body. It can walk quickly, avoid obstacles quickly, climb steadily up and down slopes, and resist impact interference. You can now take it home! Fourier Intelligence's universal humanoid robot GR-1 has started pre-sale. Robot Lecture Hall Fourier Intelligence's Fourier GR-1 universal humanoid robot has now opened for pre-sale. GR-1 has a highly bionic trunk configuration and anthropomorphic motion control. The whole body has 44 degrees of freedom. It has the ability to walk, avoid obstacles, cross obstacles, go up and down slopes, resist interference, and adapt to different road surfaces. It is a general artificial intelligence system. Ideal carrier. Official website pre-sale page: www.fftai.cn/order#FourierGR-1# Fourier Intelligence needs to be rewritten.

Huawei will launch the Xuanji sensing system in the field of smart wearables, which can assess the user's emotional state based on heart rate Huawei will launch the Xuanji sensing system in the field of smart wearables, which can assess the user's emotional state based on heart rate Aug 29, 2024 pm 03:30 PM

Recently, Huawei announced that it will launch a new smart wearable product equipped with Xuanji sensing system in September, which is expected to be Huawei's latest smart watch. This new product will integrate advanced emotional health monitoring functions. The Xuanji Perception System provides users with a comprehensive health assessment with its six characteristics - accuracy, comprehensiveness, speed, flexibility, openness and scalability. The system uses a super-sensing module and optimizes the multi-channel optical path architecture technology, which greatly improves the monitoring accuracy of basic indicators such as heart rate, blood oxygen and respiration rate. In addition, the Xuanji Sensing System has also expanded the research on emotional states based on heart rate data. It is not limited to physiological indicators, but can also evaluate the user's emotional state and stress level. It supports the monitoring of more than 60 sports health indicators, covering cardiovascular, respiratory, neurological, endocrine,

What are the effective methods and common Base methods for pedestrian trajectory prediction? Top conference papers sharing! What are the effective methods and common Base methods for pedestrian trajectory prediction? Top conference papers sharing! Oct 17, 2023 am 11:13 AM

Trajectory prediction has been gaining momentum in the past two years, but most of it focuses on the direction of vehicle trajectory prediction. Today, Autonomous Driving Heart will share with you the algorithm for pedestrian trajectory prediction on NeurIPS - SHENet. In restricted scenes, human movement patterns are usually To a certain extent, it conforms to limited rules. Based on this assumption, SHENet predicts a person's future trajectory by learning implicit scene rules. The article has been authorized to be original by Autonomous Driving Heart! The author's personal understanding is that currently predicting a person's future trajectory is still a challenging problem due to the randomness and subjectivity of human movement. However, human movement patterns in constrained scenes often vary due to scene constraints (such as floor plans, roads, and obstacles) and human-to-human or human-to-object interactivity.

See all articles