search
HomeBackend DevelopmentPHP TutorialPHP upload principle and operation implementation, PHP upload principle_PHP tutorial

PHP upload principle and operation implementation, PHP upload principle

Regarding the function library for PHP upload files, there are many well-packaged libraries on the Internet, and you can use them directly.

This article only talks about the principle of uploading and simple uploading operations. Old birds will ignore it ^_^~

There are also some security judgments, such as: the server restricts the ability to receive image-type files, and the client maliciously changes the suffix of the virus file to a file that matches the image type for uploading.

(For example, single file upload, the principle of multiple files remains the same, but there are a few more tricks)

PHP upload principle and operation implementation, PHP upload principle_PHP tutorialDOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ TR/xhtml1/DTD/xhtml1-transitional.dtd"> html xmlns="http://www.w3.org/1999/xhtml" xml:lang ="en"> head> meta http-equiv="Content-Type" content="text/ html;charset=UTF-8"> title>upload filestitle> head> body> form action="upload.php" enctype="multipart/form- data" method="post"> input type="hidden" name="MAX_FILE_SIZE" value="10000" /> Upload file: input type="file" name=" file"/> input type="submit" value="upload" /> form> body> html>

1. Form tag enctype attribute

In the form, enctype="multipart/form-data" is the MIME encoding used to set the form.
By default, this encoding format is application/x-www-form-urlencoded and cannot be used for file upload;
It can only be completed if multipart/form-data is used and the submission method is Post transfer file data.

2. MAX_FILE_SIZE hidden field

MAX_FILE_SIZE The hidden field (unit is bytes) must be placed before the file input field, and its value is the maximum size of the received file. This is a recommendation for browsers, PHP will also check this.
This setting can be easily bypassed on the browser side, so don't expect to use this feature to block large files. (However, in view of friendliness, it is better to add this item to the form, because it can avoid the trouble of users spending time waiting to upload large files only to find that the file is too large and the upload failed.)

upload.php

<?<span>php    
    </span><span>print_r</span>(<span>$_FILES</span><span>);
</span>?>

We can see:

<span>Array</span><span>
(
    [</span><span>file</span>] => <span>Array</span><span>
        (
            [name] </span>=> 照片文件.<span>jpg
            [type] </span>=> image/<span>jpeg
            [tmp_name] </span>=> F:\wamp\tmp\php41BB.<span>tmp
            [error] </span>=> 0<span>
            [size] </span>=> 73886<span>
        )

)</span>

3. Application of global variable $_FILES

$_FILES['file']['name'] is the original file name of the uploaded file

 $_FILES['file']['type']  is the MIME type of the uploaded file

 $_FILES['file']['size'] The size of the uploaded file, in bytes

 $_FILES['file']['tmp_name'] The temporary file name () stored on the server after the file is uploaded

$_FILES['file']['error'] File upload error code

4. By default, the uploaded file will be saved in the temporary folder on the server, and its directory is set in php.ini

Some common settings in php.ini related to file upload:

file_uploads ; Switch whether to allow file uploads via HTTP. The default is ON

upload_tmp_dir ; Files are uploaded to the server where temporary files are stored. If not specified, the system default temporary folder will be used

upload_max_filesize; That is the maximum size of files allowed to be uploaded. Default is 2M

post_max_size; refers to the maximum value that can be received through form POST to PHP, including all values ​​in the form. The default is 8M

The following is the complete code for single file upload. Because it is written as I wish, the logic may be a bit messy. Understanding the principle is the most important thing.

<?<span>php
    
    </span><span>//</span><span>取得上传文件信息</span>
    <span>$fileName</span>=<span>$_FILES</span>['file']['name'<span>];
    </span><span>$fileType</span>=<span>$_FILES</span>['file']['type'<span>];
    </span><span>$fileError</span>=<span>$_FILES</span>['file']['error'<span>];
    </span><span>$fileSize</span>=<span>$_FILES</span>['file']['size'<span>];
    </span><span>$tempName</span>=<span>$_FILES</span>['file']['tmp_name'];<span>//</span><span>临时文件名
    
    //定义上传文件类型</span>
    <span>$typeList</span> = <span>array</span>("image/jpeg","image/jpg","image/png","image/gif"); <span>//</span><span>定义允许的类型</span>

    <span>if</span>(<span>$fileError</span>>0<span>){
            </span><span>//</span><span>上传文件错误编号判断</span>
            <span>switch</span> (<span>$fileError</span><span>) {
                </span><span>case</span> 1:
                    <span>$message</span>="上传的文件超过了php.ini 中 upload_max_filesize 选项限制的值。"<span>; 
                    </span><span>break</span><span>;
                </span><span>case</span> 2:
                    <span>$message</span>="上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值。"<span>; 
                    </span><span>break</span><span>;
                </span><span>case</span> 3:
                    <span>$message</span>="文件只有部分被上传。"<span>; 
                    </span><span>break</span><span>;
                </span><span>case</span> 4:
                    <span>$message</span>="没有文件被上传。"<span>;
                    </span><span>break</span><span>;
                </span><span>case</span> 6:
                    <span>$message</span>="找不到临时文件夹。"<span>; 
                    </span><span>break</span><span>;
                </span><span>case</span> 7:
                    <span>$message</span>="文件写入失败"<span>; 
                    </span><span>break</span><span>;
                </span><span>case</span> 8:
                    <span>$message</span>="由于PHP的扩展程序中断了文件上传"<span>;
                    </span><span>break</span><span>;
            }

            </span><span>exit</span>("文件上传失败:".<span>$message</span><span>);

        }
    </span><span>if</span>(!<span>is_uploaded_file</span>(<span>$tempName</span><span>)){
        </span><span>//</span><span>判断是否是POST上传过来的文件</span>
        <span>exit</span>("不是通过HTTP POST方式上传上来的"<span>);
    }</span><span>else</span><span>{
        </span><span>if</span>(!<span>in_array</span>(<span>$fileType</span>, <span>$typeList</span><span>)){
            </span><span>exit</span>("上传的文件不是指定类型"<span>);
        }</span><span>else</span><span>{
            </span><span>if</span>(!<span>getimagesize</span>(<span>$tempName</span><span>)){
                </span><span>//</span><span>避免用户上传恶意文件,如把病毒文件扩展名改为图片格式</span>
                <span>exit</span>("上传的文件不是图片"<span>);
            }
        }
            </span><span>if</span>(<span>$fileSize</span>>100000<span>){
                </span><span>//</span><span>对特定表单的上传文件限制大小</span>
                <span>exit</span>("上传文件超出限制大小"<span>);
            }</span><span>else</span><span>{
                </span><span>//</span><span>避免上传文件的中文名乱码</span>
                <span>$fileName</span>=<span>iconv</span>("UTF-8", "GBK", <span>$fileName</span>);<span>//</span><span>把iconv抓取到的字符编码从utf-8转为gbk输出</span>
                <span>$fileName</span>=<span>str_replace</span>(".", <span>time</span>().".", <span>$fileName</span>);<span>//</span><span>在图片名称后加入时间戳,避免重名文件覆盖</span>
                <span>if</span>(<span>move_uploaded_file</span>(<span>$tempName</span>, "uploads/".<span>$fileName</span><span>)){
                    </span><span>echo</span> "上传文件成功!"<span>;
                }</span><span>else</span><span>{
                    </span><span>echo</span> "上传文件失败"<span>;
                }
            }

        }

</span>?>

5. Some common functions for uploading files in PHP: (I won’t post the specific usage, just read the API documentation yourself ^_^)

file_exists Check whether the file or directory exists

is_uploaded_file Determine whether the file is uploaded via HTTP POST

move_uploaded_file Move the uploaded file to a new location

is_writable Determine whether the given file name is writable

iconv Character encoding conversion

str_replace String replacement (change file name, prevent duplicate names)

getimagesize Check whether it is an image file (other types of files can be detected even if the suffix name is changed)

php implements log management (Recording user operations) Principle

What is implemented separately is to implement the login log and the operation log, customize the number of two functions, and DO these two functions respectively when the user logs in, adds, modifies and deletes. The information is recorded in the database table.

How to implement the progress bar function when uploading php files?

Don’t be so troublesome. There are many plug-ins for jquery that can realize the style of uploading file progress. You can use it

ps: Since you are such a personality, I will tell you the principle of implementation. The specific details are yourselves. Go ahead and do it.

Ordinary page access is all synchronous, that is, request-->feedback, and the progress bar requires real-time data, so ordinary pages cannot achieve this function, and you need to use asynchronous Ajax cycles to obtain progress data. The source of this data is of course sent by the server. This encounters a serious problem. PHP cannot obtain the status of the file transfer process. Fortunately, the founder of PHP wrote an APC extension (in addition An extension is uploadprogress), using the extended syntax, adding ajax, and using js to operate the DOM object of the page, the progress bar is realized.
You understand the principle, but it is difficult for you to make it, hey.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/853719.htmlTechArticlePHP upload principle and operation implementation, php upload principle Regarding the function class library for PHP upload files, there are many encapsulation packages on the Internet Perfect, everyone can use it directly. This article just talks about...

Statement
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
What is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

What is a session in PHP, and why are they used?What is a session in PHP, and why are they used?May 04, 2025 am 12:12 AM

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

Explain the lifecycle of a PHP session.Explain the lifecycle of a PHP session.May 04, 2025 am 12:04 AM

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

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 Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment