


PHP file upload processing logic review (comprehensive analysis)
This article will introduce to you the logic implementation analysis of PHP file upload. This kind of implementation must be relatively common in projects. Let's take a look~ I hope it will be helpful to friends in need~
File name processing
The file name depends on the business requirements. If there is no need to retain the original name, just randomly generate the name and add the suffix verified by the whitelist. [Recommended learning: PHP video tutorial]
On the contrary, handle it with caution:
//允许上传的后缀白名单 $extension_white_list = ['jpg', 'pdf']; //原始文件的名字 $origin_file_name = 'xx/xxx/10月CPI同比上涨2.1%.php.pdf'; //提取文件后缀,并校验是否在白名单内 $extension = strtolower(pathinfo($origin_file_name, PATHINFO_EXTENSION)); if (!in_array($extension, $extension_white_list)) { die('错误的文件类型'); } //提取文件名 $new_file_name = pathinfo($origin_file_name, PATHINFO_BASENAME); //截取掉后缀部分 $new_file_name = mb_substr($new_file_name, 0, mb_strlen($new_file_name) - 1 - mb_strlen($extension)); //只保留有限长度的名字 $new_file_name = mb_substr($new_file_name, 0, 20); //替换掉所有的 . 避免攻击者构造多后缀的文件,缺点是文件名不能包含 . $new_file_name = str_replace('.', '_', $new_file_name); //把处理过的名字和后缀拼接起来构造成一个名字 $new_file_name = $new_file_name . '.' . $extension; print_r($new_file_name); //10月CPI同比上涨2_1%_php.pdf
File content processing
The file suffix is just On the surface, changing the suffix of a PHP file to jpg cannot change the fact that it carries PHP code.
For image files, you can read the image file header to determine the image type. Of course, I have not tested this method. If you are interested, you can test it yourself.
In addition, even if the above method is feasible, it can still be bypassed. Just write the bytes of the header characteristics of a certain image type in the header of the php file to disguise it.
For image file content processing, the real trick is to redraw the image.
Use the copy command under the windows system to create an image file containing php code. The command is as follows:
Copy 1.jpg/b + test.php/a 2.jpg
The above command means to merge test.php to the end of 1.jpg. And re-export it to 2.jpg. In this way, this 2.jpg is an image file containing PHP code. You can open it with Notepad and drag the scroll bar to the bottom to see the PHP code.
For unclean pictures like this, you can remove the unclean parts by redrawing the picture. The following is the php code to redraw the image:
try { $jpg = '包含php代码的.jpg'; list($width, $height) = getimagesize($jpg); $im = imagecreatetruecolor($width, $height); $image = imagecreatefromjpeg($jpg); imagecopyresampled($im, $image, 0, 0, 0, 0, $width, $height, $width, $height); $target = '重绘后干净的图片.jpg'; imagejpeg($image, $target); } finally { isset($im) && is_resource($im) && imagedestroy($im); isset($image) && is_resource($image) && imagedestroy($image); }
The disadvantages of this method are that it consumes memory, the image is distorted, and it can only process images.
Of course, I don’t know if other file formats can be processed using the redrawing method.
File permission processing
Only discuss the permissions under Linux, first briefly introduce the permissions under Linux:
读取,字母 r 或数字 4 表示 写入,字母 w 或数字 2 表示 执行,字母 x 或数字 1 表示
For files, rwx is as follows Meaning:
r:可打开读取此文件 w:可写入此文件 x:可执行此文件
For directories, the meaning of rwx is a little different:
r:可读取此目录的内容列表 w:可在此目录里面进行:增、删、改文件和子目录 x:可进入此目录
In addition, in Linux, users will be divided into three types for a file, namely: Create the file A user who is in the same group as the user who created the file, who is neither the creator nor another user in the same group.
With the understanding of Linux permissions, 755 permissions should be set for the directory where the uploaded file is located, which means:
The user who created the directory has read access , write and enter permissions to this directory
Users in the same user group as the user who created the directory have permissions to read and enter this directory
Neither the creator nor other users in the same group have permission to read and enter this directory.
755 permission setting allows nginx to proxy static files. No 403 error will be reported.
Code example:
mkdir($save_path, 0755, true);
For uploaded files, use more stringent permission settings. 644 permissions should be set, which means:
Create The user of this file has the permission to read and write this file and cannot execute it
Users in the same user group as the user who created the file only have read permission
Other users who are neither the creator nor the same group only have read permission
644 permission settings, which ensures that even if an illegal file is uploaded It is also impossible to change the content and execute it.
Code example:
chmod($file, 0644);
File server processing
Purchase money to buy an oss storage service, don’t even think about it, just throw it in .
Original address: https://learnku.com/articles/73100
Author’s blog: https://learnku.com/blog/buexplain
The above is the detailed content of PHP file upload processing logic review (comprehensive analysis). For more information, please follow other related articles on the PHP Chinese website!

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











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,

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.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.
