PHP implementation file upload and multiple file upload _php skills

Source: Internet
Author: User
Tags php server php and php file upload upload php

In PHP program development, File upload is a very common use of the function, but also a PHP programmer the necessary skills. Happily, it is much simpler to implement file uploads in PHP than in languages like Java and C #. Below we combine specific code examples to detail how to implement file upload and multiple file upload function through PHP.

To use PHP to implement the file upload function, we first write two PHP files: index.php and upload.php. Where the index.php page is used to submit a form request for a file upload, the upload.php page is used to receive uploaded files and handle them accordingly.

First of all, we write a simple index.php file, because it involves the main HTML code, relatively simple, so no longer repeat, the detailed code of the index.php page is as follows:

<?php
//Set code for UTF-8 to avoid Chinese garbled
header (' Content-type:text/html;charset=utf-8 ');
? >
<! DOCTYPE html>
 
 

Notably, because it does not support file upload at the beginning of the HTTP protocol design, the default value for the form form's Encrypt property is application/x-www-form-urlencoded, which can only be used to submit a general form request. If the submitted form contains files that need to be uploaded, we need to change the Enctype attribute value to Multipart/form-data to achieve the file upload function. Additionally, the property value of method must be post.

Next, we continue to write code for the upload.php file.

 <?php//set encoding to UTF-8 to avoid Chinese garbled header (' content-type:text/html;charset=utf-8 '); $first _file = $_files[' Upload_file1 ']; Get information on file 1 $second _file = $_files[' Upload_file2 '];  Get information for file 2 $upload_dir = ' d:/upload/'; Save uploaded file directory//process uploaded file 1 if ($first _file[' error '] = = UPLOAD_ERR_OK) {//Upload file 1 temporary storage path on server $temp = $first _file[' Tmp_na
  Me '];
  Upload file 1 The real name on the client computer $file _name = $first _file[' name '];
  Move file 1 in the temporary folder to the directory where the uploaded files are stored, and rename the real name Move_uploaded_file ($temp _name, $upload _dir. $file _name);
Echo ' [File 1] upload successful!<br/> ';

}else{echo ' [File 1] upload failed!<br/> ';}
  Process uploaded file 2 if ($second _file[' error '] = = UPLOAD_ERR_OK) {//Upload file 2 temporary storage path on server $temp = $second _file[' tmp_name '];
  Upload file 2 The real name on the client computer $file _name = $second _file[' name '];
  Move file 2 in the temporary folder to the directory where the uploaded files are stored, and rename the real name Move_uploaded_file ($temp _name, $upload _dir. $file _name);
Echo ' [File 2] upload successful!<br/> '; }else {echo ' [File 2] upload failed!<br/> ';}?> 

In PHP, when the browser client submits a form request that contains the uploaded file, php temporarily stores the uploaded file in the temporary directory (the default temporary directory in the Windows operating system is typically c:/windows/temp). Then, the relevant information of the uploaded file is stored in the $_files of the Super global variable. Therefore, we only need to get the uploaded file information through the $_files array, and then do the corresponding processing operation. Let's take a look at the details of using the Print_r () function to output the Super global variable $_files when uploading a.gif and b.gif two picture files through the browser:

Array ([Upload_file1] => Array ( 
 [name] => a.gif (real file name when client uploads)
 [type] => image/gif (type of file)
 [tmp_n AME] => C:\Windows\Temp\php9803.tmp (the path that is temporarily stored on file after uploading to the PHP server)
 [ERROR] => 0 (wrong message, 0 means no error)
 [size] => 87123 (file size, in bytes)
    [Upload_file2] => Array (
 [name] => b.gif
 [type] => image/gif
 [tmp_name] => C:\Windows\Temp\ Php9813.tmp
 [ERROR] => 0
 [size] => 93111
 )
)

In the example above, we uploaded the two file parameter names Upload_file1 and Upload_file2 respectively. Now that we have multiple files in the form upload_file with the same parameter name, we will submit the two files that we just uploaded as a parameter array again. At this point, we need to modify the two file fields in the index.php page to the following HTML code:

    • File 1:<input name= "upload_file[]" type= "file"/><br/>
    • File 2:<input name= "upload_file[]" type= "file"/><br/>

In addition, we need to modify the upload.php page accordingly:

<?php
//Set code for UTF-8 to avoid Chinese garbled
header (' Content-type:text/html;charset=utf-8 ');
$fileArray = $_files[' upload_file '];//get information about multiple files, note: The key name here does not contain []

$upload _dir = ' d:/upload/';//Save directory
of uploaded files foreach ($fileArray [' Error '] as $key => $error) {
  if ($error = = UPLOAD_ERR_OK) {//php constant upload_err_ok=0, indicating that the upload did not Wrong
    $temp _name = $fileArray [' Tmp_name '] [$key];
    $file _name = $fileArray [' name '] [$key];
    Move_uploaded_file ($temp _name, $upload _dir. $file _name);
    echo ' upload [file '. $key. '] Success!<br/> ';
  } else {
    echo ' uploads [file '. $key. '] Failed!<br/> ';
  }
? >

Similarly, we use the Print_r () function to view the details of the Super global variable $_files in the above example:

Array ( 
 [upload_file] => Array ([ 
 name] => Array ( 
  [0] => a.gif
  [1] => b.gif  
  ) 
 [type] => Array ( 
  [0] => image/gif
  [1] => image/gif  
  ) 
 [Tmp_name] => Array (
  [0] => C:\Windo Ws\temp\php87b9.tmp
  [1] => C:\Windows\Temp\php87BA.tmp
  ) 
 [ERROR] => Array ( 
  [0] => 0
  [1] => 0  
  ) 
 [Size] => Array ( 
  [0] => 87123
  [1] => 93111  
  )
 )

Note 1: In the PHP default configuration, upload the file size beyond a certain range will be wrong, please see the end of the article mentioned how to modify the PHP upload file size limit problem solution.
Note 2: The above processing file upload PHP code is just a simple introductory example, and can not be used directly as a formal code, because there are many security factors that need extra attention are not considered, such as: file type, file size and upload file name duplication.
Note 3: If the uploaded file name contains Chinese, it may cause the file name garbled problem. At this point, you need to use the function iconv () to convert the encoding of the file name.

We learned how to use PHP to implement file uploads and multiple file uploads. However, in the default configuration of PHP, when the uploaded file size exceeds a certain limit, we will get the following error message:

Warning:post content-length of 625523488 bytes exceeds the limit of 8388608 bytes in Unknown on line 0
the general meaning of the above error message is that I The amount of data submitted using a POST request exceeds the maximum number of servers (8388608 bytes =8mb).

the reason for this error is that, in the PHP configuration file php.ini, the following configuration information exists by default (in PHP.ini, the semicolon at the beginning of the line). Indicates that the current line is a comment and does not take effect: the

maximum time allowed by the script to resolve input data (similar to POST and get), in seconds. It is measured from all data received to the beginning of the execution of the script. 
max_input_time =

n; maximum data to be sent by a client on a single POST request
post_max_size = 8M

; open File Upload function
file_uploads =

on Temporary storage directory for file uploads (if not specified, use system default temp directory)
; upload_tmp_dir =

; maximum file size allowed for a single request upload
upload_max_filesize = 2M

; Maximum number of files allowed for a single post request to be uploaded simultaneously
max_file_uploads = 20

From the configuration information above, we can see that PHP's default configuration information is to cause the PHP file upload when the file size exceeded the limit of the "culprit." The author has given in the above configuration information to each instruction option corresponding Chinese annotation information, everybody may according to own actual demand situation to the php.ini configuration file to make the corresponding modification.

The above is the entire content of this article, to help you realize php file upload function.

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.