Home Backend Development PHP Tutorial PHP file upload processing logic review (comprehensive analysis)

PHP file upload processing logic review (comprehensive analysis)

Nov 10, 2022 pm 04:32 PM
php File Upload

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
Copy after login

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
Copy after login

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);
}
Copy after login

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 表示
Copy after login

For files, rwx is as follows Meaning:

r:可打开读取此文件
w:可写入此文件
x:可执行此文件
Copy after login

For directories, the meaning of rwx is a little different:

r:可读取此目录的内容列表
w:可在此目录里面进行:增、删、改文件和子目录
x:可进入此目录
Copy after login

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);
Copy after login

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);
Copy after login

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!

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

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks 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)

Hot Topics

Java Tutorial
1665
14
PHP Tutorial
1269
29
C# Tutorial
1249
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

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 in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

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: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

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

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

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.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

See all articles