PHP Upload file Problem Summary _php instance

Source: Internet
Author: User
Tags html form

1. Make a simple upload file first

Copy Code code as follows:

<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 ">
<body>
<form action= "upload_file.php" method= "POST"
Enctype= "Multipart/form-data" >
<label for= "File" >Filename:</label>
<input type= "File" name= "file" id= "file"/>
<br/>
<input type= "Submit" name= "submit" value= "Submit"/>
</form>
</body>

Copy Code code as follows:

<?php
if ($_files["file" ["Size"] < 20000)
{
if ($_files["file"] ["error"] > 0)
{
echo "Return Code:". $_files["File" ["Error"]. "<br/>";
}
Else
{
echo "Upload:". $_files["File" ["Name"]. "<br/>";
echo "Type:". $_files["File" ["type"]. "<br/>";
echo "Size:". ($_files["File"] ["size"]/1024). "Kb<br/>";
echo "Temp file:". $_files["File" ["Tmp_name"]. "<br/>";
if (file_exists ("upload/". $_files["File" ["Name"])
{
echo $_files["File" ["Name"]. "already exists."
}
Else
{
Move_uploaded_file ($_files["file"] ["Tmp_name"],
"Upload/". $_files["File" ["name"]);
echo "Stored in:". Upload/". $_files["File" ["Name"];
}
}
}
Else
{
echo "Invalid file";
}
?>

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

Copy Code code as follows:

$_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 its value is 0, no error occurred, file upload success.

Upload_err_ini_size the value is 1, the uploaded file exceeds the upload_max_filesize option limit in php.ini.

Upload_err_form_size the value is 2, the size of the upload 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 The value is 6, the temporary folder cannot be found. PHP 4.3.10 and PHP 5.0.3 introduced.

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

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

We know that it is unwise to use $_files[' userfile ' [' type '] to judge the type of upload file, because it is based on the suffix name of the file, and anyone can change the suffix of a mp3 file into JPG to disguise it as a picture upload, So PHP official proposed to use PHP extension php_fileinfo to judge the file mime, open the way to expand Baidu there are a lot of, win and Linux slightly different.

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

Copy Code code as follows:

if (File_exists ("./upload/". $_files["File" ["Name"])
{
do{
$suffix = "";
$suffix _length = 4;
$str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$len = strlen ($str)-1;
Append 4 random characters after file name
for ($i =0; $i < $suffix _length; $i + +) {
$suffix. = $str [rand (0, $len)];
}
$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));
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 catalogue

Copy Code code as follows:

$structure = './'. Date ("Y"). ' /'. Date ("M"). ' /'. Date ("D"). ' /';
if (!mkdir ($structure, 0777, True)) {
Die (' Failed to create folders ... ');
}
Move_uploaded_file ($_files["file"] ["Tmp_name"], $structure. $_files["File" ["name"]);

6. Scenario Three: Multiple file uploads

Copy Code code as follows:

<form action= "" method= "Post" enctype= "Multipart/form-data" >
<p>pictures:
<input type= "File" Name= "pictures[]"/>
<input type= "File" Name= "pictures[]"/>
<input type= "File" Name= "pictures[]"/>
<input type= "Submit" value= "Send"/>
</p>
</form>

Copy Code code as follows:

<?php
foreach ($_files["Pictures"] ["error"] as $key => $error) {
if ($error = = UPLOAD_ERR_OK) {
$tmp _name = $_files["Pictures" ["Tmp_name"] [$key];
$name = $_files["Pictures" ["Name"] [$key];
Move_uploaded_file ($tmp _name, "data/$name");
}
}
?>


In some cases, this variable structure of multiple files is not easy to use:

Copy Code code as follows:

Array (1) {
["Upload"]=>array (2) {
[' Name ']=>array (2) {
[0]=>string (9) "File0.txt"
[1]=>string (9) "File1.txt"
}
[' Type ']=>array (2) {
[0]=>string (Text/plain)
[1]=>string (text/html)
}
}
}


In many cases, we need a structure like this.

Copy Code code as follows:

Array (1) {
["Upload"]=>array (2) {
[0]=>array (2) {
[' Name ']=>string (9) ' File0.txt '
[' Type ']=>string (Text/plain]
},
[1]=>array (2) {
[' Name ']=>string (9) ' File1.txt '
[' Type ']=>string (text/html]
}
}
}

You can easily transform the structure using the following function

Copy Code code as follows:

function Diverse_array ($vector) {
$result = Array ();
foreach ($vector as $key 1 => $value 1)
foreach ($value 1 as $key 2 => $value 2)
$result [$key 2][$key 1] = $value 2;
return $result;
}
$upload = Diverse_array ($_files["upload"]);

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

First, on the form

<input type= "hidden" name= "max_file_size" value= "bytes"/>
You can limit the size of the upload file (can be bypassed).

Then you need to adjust the configuration on the server

Ini:

Copy Code code as follows:

Max_execution_time = 30 Maximum time per script to run, in seconds
Max_input_time = 60, the time each script can consume, the unit is also seconds
Memory_limit = 128M, which is the maximum memory consumed by the script
Post_max_size = 8M, form submission maximum data is 8M, this is not to limit the size of uploading individual files, but to the entire form of submission data restrictions.
Upload_max_filesize = 2M, maximum allowable size of uploaded file

Nginx:

Copy Code code as follows:

Location/{
root HTML;
Index index.html index.htm;
Client_max_body_size 1000m;
}

Summarize these for the time being, hope the small friends can like.

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.