PHP upload principle and operation implementation, PHP upload principle _php Tutorial

Source: Internet
Author: User
Tags form post html form http post php file upload

PHP upload principle and operation implementation, PHP upload principle


About PHP upload file function class Library, there are many packages on the Internet is perfect, we can directly use it.

This article is just about the upload principle and simple upload operation, the veteran will ignore ha ^_^ ~

There are some security judgments, such as: Server limit can receive image types of files, and the client maliciously to the virus file suffix name to image matching file upload.

(for example, single file upload, multi-file principle is still unchanged, but a little bit more tips)

DOCTYPE HTML Public "-//W3C//DTD XHTML 1.0 transitional//en" "http://www.w3.org/TR/xhtml1/DTD/ Xhtml1-transitional.dtd "><HTMLxmlns= "http://www.w3.org/1999/xhtml"Xml:lang= "en"><Head> <Metahttp-equiv= "Content-type"content= "Text/html;charset=utf-8"> <title>Upload files title>!-- Head ; < Body ; < form Action = "upload.php" enctype = "Multipart/form-data" Method = "POST" ; < input type = "hidden" name = "Max_file_size" value = "10000" /> Uploading Files: < input type = "File" name = "File" /> < input type = "Submit" value = "Upload" /> !-- form ; !-- Body ; !-- HTML ;

1. Form Tag Enctype Property

The enctype= "Multipart/form-data" in the form is the MIME encoding used to set up the form.
By default, this encoding format is application/x-www-form-urlencoded and cannot be used for file uploads;
Only the multipart/form-data is used and the submission method is Post for full file data transfer.

2. MAX_FILE_SIZE Hidden Fields

max_file_size hidden Fields (in bytes) must precede the file input field with a value of the maximum size of the received file. This is a suggestion for the browser, PHP will also check this.
This setting can be bypassed easily on the browser side, so do not expect this feature to block large files. (However, it is best to add this item to the form because it avoids the hassle of having to wait for a large file to be uploaded before the user discovers that the file is too large to upload.) )

upload.php

 
  PHP        print_r($_files);? >

We can see:

Array (    [fileArray        (            = = Photo file.  JPG            = image/jpeg            = F:\wamp\tmp\php41BB.  TMP            = 0            = 73886        ))

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 files, in bytes

$_files[' file ' [' Tmp_name '] files are uploaded and stored on the server after the temporary file name ()

$_files[' file ' [' Error '] upload error code

4, by default, the upload file will be saved in the server side of the temporary folder, its directory in the php.ini set

PHP.ini some common settings related to file uploads:

file_uploads; Whether to allow the switch to upload files over HTTP. The default is on, which is open

Upload_tmp_dir; Files are uploaded to the server where temporary files are stored, and if not specified, the system default Temp folder is used

upload_max_filesize; That is, the maximum size allowed for uploading files. Default is 2M

post_max_size; Refers to the maximum value that can be received by a form post to PHP, including all values in the form. Default is 8M

The following is a single file upload complete code, because it is random with write, may be a bit of logic nesting, understand the principle of the most important.

 Php//Get upload file information    $fileName=$_files[' File '] [' Name ']; $fileType=$_files[' File '] [' Type ']; $fileError=$_files[' File '] [' Error ']; $fileSize=$_files[' File '] [' Size ']; $tempName=$_files[' File '] [' Tmp_name '];//temp file name//definition upload file type    $typeList=Array("Image/jpeg", "image/jpg", "Image/png", "image/gif");//define the allowed types    if($fileError>0){            //Upload file error number judgment            Switch($fileError) {                 Case1:$message= "The uploaded file exceeds the value of the Upload_max_filesize option limit in php.ini. ";  Break;  Case2:$message= "The size of the uploaded file exceeds the value specified by the Max_file_size option in the HTML form." ";  Break;  Case3:$message= "The file is only partially uploaded. ";  Break;  Case4:$message= "No files were uploaded." ";  Break;  Case6:$message= "The Temp folder could not be found." ";  Break;  Case7:$message= "File Write Failed";  Break;  Case8:$message= "File upload interrupted due to PHP extension";  Break; }            Exit("File Upload failed:".)$message); }    if(!Is_uploaded_file($tempName)){        //determine if it is a post-uploaded file.        Exit("not uploaded by HTTP POST"); }Else{        if(!In_array($fileType,$typeList)){            Exit("uploaded file is not a specified type"); }Else{            if(!getimagesize($tempName)){                //prevent users from uploading malicious files, such as changing the virus file name extension to picture format                Exit("The uploaded file is not a picture"); }        }            if($fileSize>100000){                //limit the size of upload files for specific forms                Exit("Upload file exceeds the limit size"); }Else{                //avoid uploading files in Chinese name garbled                $fileName=Iconv("UTF-8", "GBK",$fileName);//Convert the character encoding Iconv crawled from utf-8 to GBK output                $fileName=Str_replace(".", Time().".",$fileName);//Add a timestamp after the name of the image to avoid overwriting files with duplicate names                if(Move_uploaded_file($tempName, "uploads/".$fileName)){                    Echo"Upload the file successfully!" "; }Else{                    Echo"Upload file Failed"; }            }        }?>

5, about the PHP upload files of some common functions: (The specific usage is not posted out, look at the API document Bar ^_^)

file_exists Checking whether a file or directory exists

is_uploaded_file To determine if the file was uploaded via HTTP POST

move_uploaded_file Moving uploaded files to a new location

is_writable Determines whether a given file name can be written

iconv character encoding for mutual transfer

str_replace string substitution (change filename, anti-duplicate name)

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


PHP implementation Log management (record user action) principle

The implementation of the implementation of the log and operation log, the number of custom 2 functions, when the user login and add, modify and delete do the two functions respectively. The information is recorded in the database table.

PHP file upload, how to achieve progress bar work can?

Not so troublesome, jquery has a lot of plug-ins to achieve the upload file progress style, you can use the next

PS: Since you are so personality, I will give you the principle of implementation, specific details you do it yourself.

Normal page access is all synchronous, is the request-to-feedback, and the progress bar needs real-time data, so the normal page is not able to achieve this function, it is necessary to use the asynchronous Ajax cycle to obtain progress data, the source of course is the server sent, so that encountered a serious problem, PHP does not get the status of the file transfer process. Fortunately, the PHP founder wrote an APC extension (another extension is uploadprogress), using the extended syntax, plus Ajax, using the JS operation of the DOM object page, the implementation of the progress bar.
You understand the principle, you can hardly make it, eh.

http://www.bkjia.com/PHPjc/853719.html www.bkjia.com true http://www.bkjia.com/PHPjc/853719.html techarticle PHP upload principle and operation implementation, PHP upload the principle of PHP upload file function class Library, online there are many packaging is perfect, we can directly use it. This article is just about ...

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.