PHP Upload Files FAQ (Basic)

Source: Internet
Author: User
Tags mime file

Since the previous article, "PHP upload Chinese file name garbled problem" encountered the issue of file upload, simply put PHP upload files often encountered several problems summed up it, later use when you do not have to look for.


1. Make a simple upload file first

1 <HTML>2 <Head>3 <Metahttp-equiv= "Content-type"content= "text/html; charset=utf-8">4 
  Head>5 <Body>6 7 <formAction= "upload_file.php"Method= "POST"8 enctype= "Multipart/form-data">9 <label for= "File">Filename: 
     label> <input  type= "File"  Name= "file"  ID= "file" />  <BR  /> <input  type= "Submit"  name  = "Submit " value= "Submit" />  
       Form>   
       body >  
        html>  
    
   
 

1 
 Php2 if(($_files["File"] ["Size"] < 20000)3   {4   if($_files["File"] ["error"] > 0)5     {6     Echo"Return Code:".$_files["File"] ["Error"]. "
";7 } 8 Else9 {Ten Echo"Upload:".$_files["File"] ["Name"]. "
"; One Echo"Type:".$_files["File"] ["Type"]. "
"; A Echo"Size:". ($_files["File"] ["Size"]/1024). The Kb
"; - Echo"Temp file:".$_files["File"] ["Tmp_name"]. "
"; - the if(file_exists("upload/".$_files["File"] ["Name"])) - { - Echo $_files["File"] ["Name"]. "already exists."; - } + Else - { + Move_uploaded_file($_files["File"] ["Tmp_name"], A"Upload/".$_files["File"] ["Name"]); at Echo"Stored in:". Upload/".$_files["File"] ["Name"]; - } - } - } - Else - { in Echo"Invalid file"; - } to?>

2. Then understand the value of the Super global variable $_files

$_files[' UserFile ' [' Name ']

$_files[' userfile ' [' type ']

$_files[' userfile ' [' Size ']

$_files[' UserFile ' [' Tmp_name ']

$_files[' userfile ' [' Error ']

where all values of $_files[' userfile ' [' Error '] are:

Upload_err_ok The value is 0, no error occurred and the file upload was successful.

Upload_err_ini_size has a value of 1, the uploaded file exceeds the value of the Upload_max_filesize option limit in php.ini.

Upload_err_form_size its value is 2, the size of the uploaded file exceeds the value specified by the Max_file_size option in the HTML form.

Upload_err_partial its value is 3, the file is only partially uploaded.

Upload_err_no_file has a value of 4 and no files are uploaded.

Upload_err_no_tmp_dir its value is 6 and cannot find a temporary folder. PHP 4.3.10 and PHP 5.0.3 introduced.

Upload_err_cant_write The value is 7, the file write fails. PHP 5.1.0 introduced.

3. Many situations: need to strictly judge the upload file type

we know that using $_files[' userfile ' [' type '] is a very unwise way to determine which file type to upload, because the decision is based on the suffix of the file, and anyone can change the suffix of a mp3 file to JPG to disguise it as a picture. Therefore, PHP official recommended to use PHP extension php_fileinfo to determine the MIME file, open the way to expand Baidu a lot, win and Linux slightly different.

4. Scenario One: Automatically rename after uploading files with duplicate name

1 if(file_exists("./upload/".$_files["File"] ["Name"]))  2 {    3     Do{  4        $suffix=""; 5        $suffix _length= 4; 6        $str= "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 7        $len=strlen($str)-1; 8        //append 4 random characters after file name9         for($i=0;$i<$suffix _length;$i++){  Ten           $suffix.=$str[Rand(0,$len)];  One        }   A        $upload _filename=$_files[' File '] [' Name '];  -        $filename=substr($upload _filename, 0,Strrpos($upload _filename,".")).$suffix.".".substr($upload _filename,Strrpos($_files["File"] ["Name"], ".") +1);  -} while(file_exists("./upload/".$filename));  the        Move_uploaded_file($_files["File"] ["Tmp_name"], "./upload/".$filename);  -}Else{   -        Move_uploaded_file($_files["File"] ["Tmp_name"], "upload/".$_files["File"] ["Name"]);  -}

5. Scenario Two: Upload files according to the date sub-catalogue

1 $structure = './'. Date ("Y"). ' /'. Date ("M"). ' /'. Date ("D"). ' /'; 2 3 4 if (! mkdir ($structuretrue)) {5die     (' Failed to create folders ... '); 6 }78move_uploaded_file($_files["File"] ["Tmp_name"],  $structure$_files["File"] ["name"]);

6. Scenario Three: Multiple file uploads

1 <formAction=""Method= "POST"enctype= "Multipart/form-data">2 <P>Pictures:3 <inputtype= "File"name= "pictures[]" />4 <inputtype= "File"name= "pictures[]" />5 <inputtype= "File"name= "pictures[]" />6 <inputtype= "Submit"value= "Send" />7  
    p>8  
     form> 
   
 

 
 1 
   PHP2foreach ($_filesas$key$error) {3     if ($error = = upload_err_ok) {4         $tmp _name$_ FILES["Pictures"] ["tmp_name"] [$key]; 5         $name $_files ["Pictures"] ["Name"] [$key]; 6         Move_uploaded_file ($tmp _name, "data/$name"); 7     }8}9 ?>

In some cases, this variable structure of multiple files is not useful:

Array (1) {

["Upload"]=>array (2) {

["Name"]=>array (2) {

[0]=>string (9) "File0.txt"

[1]=>string (9) "File1.txt"

}

["Type"]=>array (2) {

[0]=>string (Ten) "Text/plain"

[1]=>string (Ten) "Text/html"

}

}

}



In many cases, we need a structure like this.

Array (1) {

["Upload"]=>array (2) {

[0]=>array (2) {

["Name"]=>string (9) "File0.txt"

["Type"]=>string (Ten) "Text/plain"

},

[1]=>array (2) {

["Name"]=>string (9) "File1.txt"

["Type"]=>string (Ten) "Text/html"

}

}

}


The structure can be easily converted using the following function

1 function diverse_array ($vector2     $resultarray  3     foreach ($vectoras$key 1$value 14         foreach ($value 1as$key 2$value 25             $result [$key 2] [$key 1$value 26     return $result  78$upload = Diverse_array ($_files["Upload"]);

7. Sometimes: Need to configure the server to modify the maximum upload file size

First, on the form

<type= "hidden"  name= "max_file_size"  value= "byte"  />

You can limit the upload file size (which can be bypassed).

And then you need to adjust the configuration on the server.

Ini:

Max_execution_time = 30 Maximum time per script run, per second
Max_input_time = 60, each script can consume the time, the unit is also the second
Memory_limit = 128M, this is the maximum memory consumed by the script run
Post_max_size = 8M, form submission maximum data is 8M, this item is not limited to upload a single file size, but for the entire form of submission data restrictions.
Upload_max_filesize = 2M, maximum license size for uploaded files

Nginx :

1 Location /{2     root   html; 3     Index  index.html index.htm; 4      Client_max_body_size    1000m; 5  }

The above describes the PHP upload file Frequently asked questions (basic), including the aspects of the content, I hope that the PHP tutorial interested in a friend helpful.

  • 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.