Home  >  Article  >  Backend Development  >  PHP upload principle and operation implementation, PHP upload principle_PHP tutorial

PHP upload principle and operation implementation, PHP upload principle_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:21:42954browse

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 tutorial8013c8374d9f44fbd1cf27236e57a6ce 66fe2b653aca3b16f4ae8924c4b84f02 295d6adc6accb58d202b4aa5a914e90c 5b5487d9fd7ccaf1f75e891ff03d1c9d fbc1939a92f640d263f5aa2c363c0d91upload files8c88114b8e881d68c87e2d5bbbc885c9 69ff11c91593cb309ecada483e247d64 6fd585cf5dadf9f27760ae0844b0c42f 2cc72b41b2fdb0eb49600c63344e6d30 3ba43f23c62ad01db17a553493108641 Upload file: ef357bef872886d035026bd66aea6ef7 960d2c990d1c13ed566214bfde05ac4c 4d5477df51700f0daa437b62843c12de 2e0d5b0d0167a5ecee82519e3c962722 eebbc60345d5fc3018dd7f9e187c6e83

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