In-depth analysis of PHP file Upload cases (suitable for beginners)

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

With PHP, you can upload files to the server.
Create a file upload form
It is very useful to allow users to upload files from forms.
See the following HTML form for uploading files:

The code is as follows: Copy code
<Html>
<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>
</Html>

Pay attention to the following information about this form:

<Form> The enctype attribute of a tag specifies the content type to be used when submitting a form. When a form requires binary data, such as file content, use multipart/form-data ".
<Input> the type = "file" attribute of the tag specifies that the input should be processed as a file. For example, when previewing in a browser, a browser button is displayed next to the input box.
Note: allowing users to upload files is a huge security risk. Only trusted users are allowed to upload files.

Create Upload script
The "upload_file.php" file contains the code for uploading files:

The code is as follows: Copy code
<? Php
If ($ _ FILES ["file"] ["error"]> 0)
  { 
Echo "Error:". $ _ 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 "Stored in:". $ _ FILES ["file"] ["tmp_name"];
  } 
?>

By using the Global Array $ _ FILES of PHP, you can upload FILES from the client computer to a remote server.
The first parameter is the input name of the form, and the second subscript can be "name", "type", "size", "tmp_name" or "error ". Like this:
$ _ FILES ["file"] ["name"]-name of the uploaded file
$ _ FILES ["file"] ["type"]-type of the file to be uploaded
$ _ FILES ["file"] ["size"]-size of the uploaded file, in bytes
$ _ FILES ["file"] ["tmp_name"]-name of the temporary copy of the file stored on the server
$ _ FILES ["file"] ["error"]-error code caused by file upload

This is a very simple file Upload method. Based on security considerations, you should add restrictions on which users have the right to upload files.
The upload is restricted in this script. We have added the file upload restrictions. You can only upload. gif or. jpeg files. The file size must be smaller than 20 kb:

The code is as follows: Copy code
<? Php
 
If ($ _ FILES ["file"] ["type"] = "image/gif ")
| ($ _ FILES ["file"] ["type"] = "image/jpeg ")
| ($ _ FILES ["file"] ["type"] = "image/pjpeg "))
& ($ _ FILES ["file"] ["size"] <20000 ))
  { 
If ($ _ FILES ["file"] ["error"]> 0)
    { 
Echo "Error:". $ _ 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 "Stored in:". $ _ FILES ["file"] ["tmp_name"];
    } 
  } 
Else
  { 
Echo "Invalid file ";
  } 
 
?>

Note: for IE, the jpg file type must be pjpeg and for FireFox, it must be jpeg.
Save the uploaded file
In the above example, a temporary copy of the uploaded file is created in the PHP temporary folder on the server.
The temporary copy file will disappear at the end of the script. To save the uploaded file, we need to copy it to another location:

The code is as follows: Copy code
<? Php
If ($ _ FILES ["file"] ["type"] = "image/gif ")
| ($ _ FILES ["file"] ["type"] = "image/jpeg ")
| ($ _ FILES ["file"] ["type"] = "image/pjpeg "))
& ($ _ 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 ";
  } 
?>

The above script checks whether the file already exists. If it does not exist, copy the file to the specified folder.
Note: In this example, the file is saved to a new folder named "upload.

Add: a custom PHP attachment Upload class.

The code is as follows: Copy code

<? Php
/**
* File up load class
*/
Class upLoad
{
/**
 *
* @ Param string $ info file content
* @ Param string $ the file name inherent in fileName
* @ Return boolean return true if creation is successful
* @ Deprecated
* Create an html file
*/
Function createHtml ($ info, $ fileName)
 {
 }
/**
 *
* @ Return void
* @ Deprecated
* Structure functions
*/
Function downLoad ()
{}
/**
 *
* @ Param string $ field name of fileField in the form
* @ Param string $ length limit
* @ Return boolean success return true
* @ Deprecated
* Function implementation
*/
Function init ($ fileField, $ length = '')
 {
$ Files = $ _ FILES [$ fileField];
// Modify the user name based on your actual situation.
$ UserName = 'sanshi ';
$ FileName = $ files ['name'];
$ FileType = $ files ['type'];
$ FileTemp = $ files ['tmp _ name'];
$ FileSize = empty ($ length )? ($ Files ['size'] 10): $ length;
$ FileError = $ files ['error']; // This part may not exist in php4
// Change
// If ($ this-> _ isType ($ fileName) | $ this-> _ isBig ($ length ))
If (! $ This-> _ isType ($ fileName) | $ this-> _ isBig ($ length) | $ fileError! = 0)
  {
// Print_r ($ files );
Return false;
} Else {
$ Path = $ this-> _ createDir ($ userName); // Obtain the path
$ CreateFileName = $ userName. '_'. time (); // set the current file name
$ CreateFileType = $ this-> getFileType ($ fileName); // you can specify a file type.
Return @ move_uploaded_file ($ fileTemp,
$ Path. $ createFileName. '.'. $ createFileType )? True: false;
  }
 }
 
/**
 *
* @ Param int $ length indicates the maximum size of the object to be uploaded.
* @ Return boolean return true if the value is greater
* @ Deprecated
* Determine whether the specified size is exceeded.
*/
Function _ isBig ($ length)
 {
$ Bigest = '';
Return $ big> $ bigest? True: false;
}
?>

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.