Php Getting Started Tutorial single file upload and multi-file Upload instances

Source: Internet
Author: User
Tags file upload html form php file php code

Let's take a look at the content of the $ _ FILES array as follows:

$ _ FILES ['myfile'] ['name'] original name of the client file.
$ _ FILES ['myfile'] ['type'] indicates the MIME type of the file, which must be supported by the browser, for example, "image/gif ".
$ _ FILES ['myfile'] ['size'] size of the uploaded file, in bytes.
$ _ FILES ['myfile'] ['tmp _ name'] temporary file name stored on the server after the file is uploaded, which is generally the default file name. It can be specified in upload_tmp_dir of php. ini, but the putenv () function setting does not work.
$ _ FILES ['myfile'] ['error'] error code related to the file upload. ['Error'] is added in PHP 4.2.0.

The following is its description: (they become constants after PHP3.0)

UPLOAD_ERR_ OK value: 0; no error occurs. The file is uploaded successfully.
UPLOAD_ERR_INI_SIZE: 1; the uploaded file exceeds the limit of the upload_max_filesize option in php. ini.
UPLOAD_ERR_FORM_SIZE value: 2; the size of the uploaded file exceeds the value specified by the MAX_FILE_SIZE option in the HTML form.
UPLOAD_ERR_PARTIAL value: 3; only part of the file is uploaded.
UPLOAD_ERR_NO_FILE value: 4; no file is uploaded. Value: 5; the size of the uploaded file is 0.

Note:
1. After the file is uploaded, it is stored in the temporary directory by default. In this case, it must be deleted from the temporary directory or moved to another place. If it does not exist, it will be deleted. That is, no matter whether the upload is successful or not, the files in the temporary directory will be deleted after the script is executed. Therefore, you must copy the file to another location using the copy () function of PHP before deleting the file. In this case, the file upload process is completed.

2. Before PHP 4.1.0, the array name is $ HTTP_POST_FILES, which is not an automatic global variable like $ _ FILES. PHP 3 does not support the $ HTTP_POST_FILES array.

3. When using form to upload FILES, you must add the attribute content enctype = "multipart/form-data". Otherwise, an exception is reported when you use $ _ FILES [filename] to obtain file information.

The code is as follows: Copy code

<Form enctype = "multipart/form-data" action = "URL" method = "post">
<Input name = "myFile" type = "file">
<Input type = "submit" value = "Upload file">
</Form>

Php code

 

The code is as follows: Copy code
Function uploadfile ($ file ){
$ Destinationpath = "./upload /";
If (! File_exists ($ destinationpath )){
Mkdir ($ destinationpath, 0777 );}
// Rename
$ Filename = date ('ymdhis ').' _ '. iconv ('utf-8', 'gb2312', basename ($ file ['name']);
If (move_uploaded_file ($ file ['tmp _ name'], $ destinationpath. $ filename) {return iconv ('gb2312', 'utf-8', $ filename );
} Return '';
}

The principle of multifile upload is similar. Let's take a look at the example below.

 

The code is as follows: Copy code

<Form action = "fileclass. php" enctype = "multipart/form-data" method = "post" id = "userfile">
<Table width = "350" border = "0" cellpadding = "0" cellspacing = "5">
<Tr>
<Td> <input name = "userfile []" type = "file" size = "30"/> </td>
</Tr>
<Input type = "hidden" name = "MAX_FILE_SIZE" value = "1000000"/>
<Tr>
<Td> <input name = "userfile []" type = "file" size = "30"/> </td>
</Tr>
<Tr>
<Td> <input name = "userfile []" type = "file" size = "30"/> </td>
</Tr>
<Tr>
<Td> <input name = "userfile []" type = "file" size = "30"/> </td>
</Tr>
<Tr>
<Td> <input name = "userfile []" type = "file" size = "30"/> </td>
</Tr>
<Tr>
<Td> <input name = "submitfile" type = "submit" value = "Confirm file upload"/> & nbsp; <input name = "resetfile" type = "reset" value = "cancel file upload"/> </td>
</Tr>
</Table>

</Form>

The fileclass. Php file code is as follows:

 

The code is as follows: Copy code

<? Php
Class more_file_upload {
Const FILE_PATH = '../filehandle/uploadfile /';
Var $ file_type;
Var $ file_type_array;
Var $ file_type_string;
Var $ file_name;
Var $ file_size;
Var $ file_tmp_name;
Var $ file_error;
Var $ handledate;
Static $ totalsize = 0;

Function _ construct ($ file_name, $ file_error, $ file_size, $ file_tmp_name, $ file_type ){
$ This-> handledate = date ('M-d-y ');
If (! Empty ($ file_name )){
$ This-> file_name = $ file_name;
$ This-> file_error = $ file_error;
$ This-> file_size = $ file_size;
$ This-> file_tmp_name = $ file_tmp_name;
$ This-> file_type = $ file_type;
$ This-> file_type_array = array ('text/plain ', 'image/GIF', 'image/jpg', 'text/html ', 'image/pjpeg ', 'image/png ', 'application/msword', 'application/pdf ');
  
$ This-> show_execute_message ($ this-> file_error, $ this-> file_name, $ this-> file_type, $ this-> file_size );
  }
 }
 
Function _ destruct (){
$ This-> file_name = NULL;
$ This-> file_error = NULL;
$ This-> file_size = NULL;
$ This-> file_tmp_name = NULL;
$ This-> file_type = NULL;
Self: $ totalsize = 0;
 }
 
Function show_execute_message ($ smfileerror, $ smfilename, $ smfiletype, $ smfilesize ){
If ($ smfileerror> 0 ){
Switch ($ smfileerror ){
Case 1: $ smfilemessage = '<strong> the file size exceeds the server's agreed size! </Strong> '; break;
Case 2: $ smfilemessage = '<strong> the file size exceeds the specified size! </Strong> '; break;
Case 3: $ smfilemessage = '<strong> only part of the file is uploaded! </Strong> '; break;
Case 4: echo "$ this-> file_name". 'file Upload failed! <Br/> '; break;
   }
Self: :__ destruct ();
} Else {
$ Smfiletypeflag = array_search ($ smfiletype, $ this-> file_type_array );
If ($ smfiletypeflag = false ){
$ Smfilemessage = '<strong> the file type is incorrect. Check the file type! </Strong> ';
Self: :__ destruct ();
} Else {
$ Resflag = $ this-> move_file ($ this-> file_tmp_name, $ this-> file_name );
If ($ resflag = 1 ){
$ Smfilemessage = 'File uploaded successfully! ';
Self: $ totalsize + = intval ($ smfilesize );
Self: :__ destruct ();
} Else {
$ Smfilemessage = '<strong> File upload failed! </Strong> ';
Self: :__ destruct ();
    }
   }
  }
$ Smfilesize = $ smfilesize/1024;
$ Smfilesizeformat = sprintf ('% 01d', $ smfilesize );
Echo '<tr>
<Td align = "left"> '. $ smfilename.' </td>
<Td align = "center"> '. $ smfiletype.' </td>
<Td align = "center"> '. $ smfilesizeformat.' </td>
<Td align = "center"> '. $ smfilemessage.' </td>
</Tr> ';
 }
 
Function move_file ($ mvfiletmp, $ mvfilename) {// move the file
$ Mvfilenamearr = explode ('.', basename ($ mvfilename ));
$ Mvtime = mktime ();
$ Mvfilenamearr [0] = $ this-> rand_string (10). "$ mvtime ";
$ Mvfilename = implode ('.', $ mvfilenamearr );

If (is_uploaded_file ($ mvfiletmp )){
$ Uploadfile = self: FILE_PATH. "$ mvfilename ";
$ Result = move_uploaded_file ($ mvfiletmp, $ uploadfile );
Return $ result;
  } 
 }

Function rand_string ($ len, $ chars = 'abcdefghijklmnopqrstuvwxyz0123456789 ') {// randomly extract characters in a specified range
$ String = '';
For ($ I = 0; $ I <$ len; $ I ++ ){
$ Pos = rand (0, strlen ($ chars)-1 );
$ String. = $ chars {$ pos };
     }
Return $ string;
 }
}
Echo '<table width = "90%" border = "1" cellpadding = "0" align = "center" cellspacing = "2"> ';
Echo '<tr>
<Td align = "center"> File Name </td>
<Td align = "center"> File type </td>
<Td align = "center"> File size (KB) </td>
<Td align = "center"> execution Result </td>
</Tr> ';
For ($ I = 0; $ I <count ($ _ FILES ['userfile']); $ I ++ ){
$ Filename [$ I] = $ _ FILES ['userfile'] ['name'] [$ I];
$ Fileerror [$ I] = $ _ FILES ['userfile'] ['error'] [$ I];
$ Filesize [$ I] = $ _ FILES ['userfile'] ['size'] [$ I];
$ Filetmpname [$ I] =$ _ FILES ['userfile'] ['tmp _ name'] [$ I];
$ Filetype [$ I] = $ _ FILES ['userfile'] ['type'] [$ I];
 
$ Filetemp = new more_file_upload ("$ filename [$ I]", "$ fileerror [$ I]", "$ filesize [$ I]", "$ filetmpname [$ I]", "$ filetype [$ I]");
}
Echo '</table> ';
Echo '<a href = "upfile.html"> continue uploading </a> <a href = "index. php"> back to homepage </a> ';
?>

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.