PHP upload principle and operation implementation, PHP upload principle_PHP tutorial

WBOY
Release: 2016-07-13 10:21:42
Original
989 people have browsed it

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

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

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

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...
Related labels:
php
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!