通常我们想严格限制文件类型的时候,可以简单地用$_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/

Reasons for PHPSession failure include configuration errors, cookie issues, and session expiration. 1. Configuration error: Check and set the correct session.save_path. 2.Cookie problem: Make sure the cookie is set correctly. 3.Session expires: Adjust session.gc_maxlifetime value to extend session time.

Methods to debug session problems in PHP include: 1. Check whether the session is started correctly; 2. Verify the delivery of the session ID; 3. Check the storage and reading of session data; 4. Check the server configuration. By outputting session ID and data, viewing session file content, etc., you can effectively diagnose and solve session-related problems.

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

Configuring the session lifecycle in PHP can be achieved by setting session.gc_maxlifetime and session.cookie_lifetime. 1) session.gc_maxlifetime controls the survival time of server-side session data, 2) session.cookie_lifetime controls the life cycle of client cookies. When set to 0, the cookie expires when the browser is closed.

The main advantages of using database storage sessions include persistence, scalability, and security. 1. Persistence: Even if the server restarts, the session data can remain unchanged. 2. Scalability: Applicable to distributed systems, ensuring that session data is synchronized between multiple servers. 3. Security: The database provides encrypted storage to protect sensitive information.

Implementing custom session processing in PHP can be done by implementing the SessionHandlerInterface interface. The specific steps include: 1) Creating a class that implements SessionHandlerInterface, such as CustomSessionHandler; 2) Rewriting methods in the interface (such as open, close, read, write, destroy, gc) to define the life cycle and storage method of session data; 3) Register a custom session processor in a PHP script and start the session. This allows data to be stored in media such as MySQL and Redis to improve performance, security and scalability.

SessionID is a mechanism used in web applications to track user session status. 1. It is a randomly generated string used to maintain user's identity information during multiple interactions between the user and the server. 2. The server generates and sends it to the client through cookies or URL parameters to help identify and associate these requests in multiple requests of the user. 3. Generation usually uses random algorithms to ensure uniqueness and unpredictability. 4. In actual development, in-memory databases such as Redis can be used to store session data to improve performance and security.

Managing sessions in stateless environments such as APIs can be achieved by using JWT or cookies. 1. JWT is suitable for statelessness and scalability, but it is large in size when it comes to big data. 2.Cookies are more traditional and easy to implement, but they need to be configured with caution to ensure security.


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

SublimeText3 English version
Recommended: Win version, supports code prompts!

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Atom editor mac version download
The most popular open source editor
