In-depth analysis of PHP File Upload cases (suitable for beginners)-PHP source code

Source: Internet
Author: User
Tags php file upload
Uploading a file refers to uploading a file from a local file to a network server. For php, it is very simple to upload a file. The following section provides an in-depth analysis of php File Uploading examples for beginners. Uploading a file refers to uploading a file from a local file to a network server. For php, it is very simple to upload a file. The following section provides an in-depth analysis of php File Uploading examples for beginners.

Script ec (2); script

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:




Pay attention to the following information about this 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 ".
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:
If ($ _ FILES ["file"] ["error"]> 0)
{
Echo "Error:". $ _ FILES ["file"] ["error"]."
";
}
Else
{
Echo "Upload:". $ _ FILES ["file"] ["name"]."
";
Echo "Type:". $ _ FILES ["file"] ["type"]."
";
Echo "Size:". ($ _ FILES ["file"] ["size"]/1024). "Kb
";
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:

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"]."
";
}
Else
{
Echo "Upload:". $ _ FILES ["file"] ["name"]."
";
Echo "Type:". $ _ FILES ["file"] ["type"]."
";
Echo "Size:". ($ _ FILES ["file"] ["size"]/1024). "Kb
";
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:
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"]."
";
}
Else
{
Echo "Upload:". $ _ FILES ["file"] ["name"]."
";
Echo "Type:". $ _ FILES ["file"] ["type"]."
";
Echo "Size:". ($ _ FILES ["file"] ["size"]/1024). "Kb
";
Echo "Temp file:". $ _ FILES ["file"] ["tmp_name"]."
";

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:

/**
* 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;
}
?>

Related Article

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.