search
HomeBackend DevelopmentPHP TutorialPHP 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!

Statement
This article is reproduced at:learnku. If there is any infringement, please contact admin@php.cn delete
How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

Simple Guide: Sending Email with PHP ScriptSimple Guide: Sending Email with PHP ScriptMay 12, 2025 am 12:02 AM

PHPisusedforsendingemailsduetoitsbuilt-inmail()functionandsupportivelibrarieslikePHPMailerandSwiftMailer.1)Usethemail()functionforbasicemails,butithaslimitations.2)EmployPHPMailerforadvancedfeatureslikeHTMLemailsandattachments.3)Improvedeliverability

PHP Performance: Identifying and Fixing BottlenecksPHP Performance: Identifying and Fixing BottlenecksMay 11, 2025 am 12:13 AM

PHP performance bottlenecks can be solved through the following steps: 1) Use Xdebug or Blackfire for performance analysis to find out the problem; 2) Optimize database queries and use caches, such as APCu; 3) Use efficient functions such as array_filter to optimize array operations; 4) Configure OPcache for bytecode cache; 5) Optimize the front-end, such as reducing HTTP requests and optimizing pictures; 6) Continuously monitor and optimize performance. Through these methods, the performance of PHP applications can be significantly improved.

Dependency Injection for PHP: a quick summaryDependency Injection for PHP: a quick summaryMay 11, 2025 am 12:09 AM

DependencyInjection(DI)inPHPisadesignpatternthatmanagesandreducesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itallowspassingdependencieslikedatabaseconnectionstoclassesasparameters,facilitatingeasiertestingandscalability.

Increase PHP Performance: Caching Strategies & TechniquesIncrease PHP Performance: Caching Strategies & TechniquesMay 11, 2025 am 12:08 AM

CachingimprovesPHPperformancebystoringresultsofcomputationsorqueriesforquickretrieval,reducingserverloadandenhancingresponsetimes.Effectivestrategiesinclude:1)Opcodecaching,whichstorescompiledPHPscriptsinmemorytoskipcompilation;2)DatacachingusingMemc

See all articles

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

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MinGW - Minimalist GNU for Windows

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.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools