PHP step-by-Step implementation of File upload and upload file class

Source: Internet
Author: User
Tags error code file upload http post ini php script unsupported

One, a relatively simple implementation of file upload


File Upload principle

File Upload principle: The client's files uploaded to the server side, and then the server-side temporary files moved to the specified directory.

Client Configuration

To upload the file, we need to use the form, and form sent to post the request, and require the enctype set to Multipart/form-data, summary upload conditions are as follows:

Browser form page

form Send As Post
Specify Enctype=multipart/form-data
Client's code:


<form action= "uploadfile.php" method= "post" accept-charset= "Utf-8" enctype= "Multipart/form-data" >
Please select the file to upload:
<input type= "File" name= "MyFile" >
<input type= "Submit" value= "Upload file" >
</form>

$_files File variables

The following is the upload of a picture and then print out the data:


Name => ' Qc8054r7qpgq_1000x500.jpg '
Type => ' Image/jpeg '
Tmp_name => '/applications/mamp/tmp/php/php1x5kzu '
Error => 0
Size => 229936

$_files upload parameter meaning description:

Name: filename of the uploaded file
Type: MIME type of uploaded file
Tmp_name: Temporary path to the server on file
Site: The size of the uploaded file
Error: Upload the wrong code for the file, 0 to upload success UPLOAD_ERR_OK

Moving files


Move File Way One
Uploading files to server side is in a temporary path, we need to move the file to the specified directory, we can use the following function to achieve the move:

Moves the specified file to the directory path
Requests that files to be moved are uploaded via an HTTP Post
BOOL Move_uploaded_file (String $filename, String $destination)

We need to determine if it is uploaded via an HTTP post, and the following methods can be used to determine:


To determine if the file was uploaded via an HTTP post, or False if it returns true
BOOL Is_uploaded_file (String $filename)

Move File Mode two

We can also use the following function to implement the move file:

Parameter one: Files to be moved
Parameter two: The target path to move to
BOOL Copy (string $source, String $dest [, Resource $context])

Processing upload


 
<?php
 
Define (' Upload_path ', ' uploads ');
 
$name = $_files[' myfile '] [' Name '];
$type = $_files[' myfile '] [' type '];
$tmp _name = $_files[' myfile '] [' tmp_name '];
$error = $_files[' myfile '] [' ERROR '];
$size = $_files[' myfile '] [' size '];
 
if ($error = = UPLOAD_ERR_OK) {
    if (is_uploaded_file ($tmp _name)) {
         Move_uploaded_file ($tmp _name, Upload_path. '/' . $NAME);
   } else {
        if (is_file ($tmp _name) &&!copy ($tmp _name, Upload_path. '/' . $name)) {
            var_dump (' OK ');
        }
   }
Else {
   ///uploaded to server has already made an error
     Var_dump ($error);
}
 
php.ini upload configuration

Suppose we want to support uploading 20M files, then we can set the following options:



Be sure to set to on to upload files, if set to OFF, the server is not receiving the file data
File_uploads = On

Specify the temporary directory to upload files to the server, default to not open, can not write
Upload_tmp_dir = "D:/uploads_tmp"

The maximum number of files that support uploading is 20M
Upload_max_filesize = 20M

Set a POST request to allow a maximum of one request of 100M
Post_max_size = 100M

The maximum time allowed for an upload operation, more than 600 seconds will stop the script running, 0 means no Limit
Max_execution_time = 600

The maximum time that the PHP script uses to parse the request data defaults to 60 seconds, and 0 means no limit
Max_input_time = 600

The maximum memory that a single PHP script can request-1 means no limit!
Memory_limit = 128M

Upload File Error code
UPLOAD_ERR_OK: On behalf of upload success
Upload_err_extension: The uploaded file was interrupted by the PHP extender
Upload_err_partial: Files are only partially uploaded
Upload_err_cant_write: File Write Failed
Upload_err_form_size: The form file exceeds the Post_max_size
Upload_err_ini_size: File size exceeded limit upload size
Upload_err_no_file: No files were uploaded
Upload_err_no_tmp_dir: Temp directory not found

Client limit Upload

We can limit the size of uploaded files by hiding the fields, and we can limit the types of uploaded files by accept, as follows:



<form action= "uploadfile.php" method= "post" accept-charset= "Utf-8" enctype= "Multipart/form-data" >
<input type= "hidden" name= "max_file_size" value= "1024" >
Please select the file to upload:
<input type= "File" Name= "MyFile" accept= "Image/png" >
<input type= "Submit" value= "Upload file" >
</form>

Service-side Limit upload

We can judge the file type, the file size, the uploading way and so on by the service side to judge whether satisfies the condition, then processes the file!



<?php

Define (' Upload_path ', ' uploads ');
Define (' Max_file_size ', 2 * 1024 * 1024);

Header (' content-type:text/html; Charset=utf-8 ');

$name = $_files[' myfile ' [' name '];
$type = $_files[' myfile '] [' type '];
$tmp _name = $_files[' myfile '] [' tmp_name '];
$error = $_files[' myfile ' [' Error '];
$size = $_files[' myfile '] [' size '];

$ALLOWEXT = Array (' png ', ' jpg ', ' jpeg ');

if ($error = = UPLOAD_ERR_OK) {
if ($size > Max_file_size) {
Exit (' uploaded file is too large ');
}

The extension type of the uploaded file
$ext = PathInfo ($name, pathinfo_extension);
if (!in_array ($ext, $allowExt)) {
Exit (' Illegal file type ');
}

if (!is_uploaded_file ($tmp _name)) {
Exit (' File not uploaded by HTTP post ');
}

if (Move_uploaded_file ($tmp _name, Upload_path. '/' . $name)) {
echo ' File upload success ';
} else {
echo "File upload failed";
}
} else {
Uploading to the server has gone wrong.
Var_dump ($error);
}

Ignore problems with duplicate file names, those that need to add some extra little processing Oh!

Second, upload file class

<?php

Ini_set (' display_errors ', ' on ');
Error_reporting (E_all);
Header (' content-type:text/html; Charset=utf-8 ');

/**
* Class for uploading a single image
*/
Class Upload {
protected $fileName; /* eg, $_files[' file ', the name is file. */
protected $allowExt; /* Allow extension for uploading a file */
protected $allowMIMEType; /* Allow uploading file mine types * *
protected $fileMaxSize; /* Limit A uploading file size * *
protected $uploadPath; /* The destination path * *
protected $isImageFlag; /* Note This is the file is a image or not. */
protected $errorMessage;
protected $fileExt;
protected $fileInfos;
protected $fileUniqueName;
protected $fileDestPath;

Public function __construct ($fileName = ' file ', $uploadPath = './uploads ', $isImageFlag = true, $fileMaxSize = 1048576, $a Llowext = Array (' png ', ' jpg ', ' jpeg ', ' gif '), $allowMIMEType = Array (' Image/png ', ' image/jpeg ', ' image/gif ')) {
$this->filename = $fileName;
$this->allowext = $allowExt;
$this->allowmimetype = $allowMIMEType;
$this->uploadpath = $uploadPath;
$this->isimageflag = $isImageFlag;
$this->filemaxsize = $fileMaxSize;
Print_r ($_files);
$this->fileinfos = $_files[$fileName];
}

Public Function UploadFile () {
if ($this->isvalidext ()
&& $this->isvalidmimetype ()
&& $this->isvalidfilesize ()
&& $this->isrealimage ()
&& $this->ishttppost ()
&& $this->haserror ()) {
$this->isuploadpathexist ();
$this->fileuniquename = $this->getuniquename ();
$this->filedestpath = $this->uploadpath. '/' . $this->fileuniquename. '.' . $this->fileext;
echo iconv (' gb2312 ', ' UTF-8 ', $this->filedestpath);
if (@move_uploaded_file ($this->fileinfos[' tmp_name '], $this->filedestpath)) {
return $this->filedestpath;
} else {
$this->errormessage = ' File upload failed ';
}
} else {
$this->errormessage = ' File upload failed ';
}

Exit (' <span style= ' color:red ' > '. $this->errormessage. ' </span> ');
}

protected function Haserror () {
$ret = true;

if (!is_null ($this->fileinfos)) {
Switch ($this->fileinfos[' ERROR ']) {
Case Upload_err_ini_size:
$this->errormessage = ' file size exceeds upload_max_filesize ' in php.ini file;
Break
Case Upload_err_form_size:
$this->errormessage = ' file size exceeds the value set in the form max_file_size ';
Break
Case UPLOAD_ERR_NO_TMP_DIR:
$this->errormessage = ' Temporary file directory not found ';
Break
Case Upload_err_no_file:
$this->errormessage = ' did not select any file upload ';
Break
Case Upload_err_cant_write:
$this->errormessage = ' File not writable ';
Break
Case Upload_err_partial:
$this->errormessage = ' Only part of the file is uploaded ';
Break
Case Upload_err_extension:
$this->errormessage = ' interrupted by PHP extender during file upload ';
Break
Default
$this->errormessage = ';
$ret = false;
}
} else {
$this->errormessage = ' error on file ';
}

return $ret;
}

protected function isvalidfilesize () {
if ($this->fileinfos[' size '] > $this->filemaxsize) {
$this->errormessage = ' file too large ';
return false;
}

return true;
}

protected function Isvalidext () {
$ext = pathinfo ($this->fileinfos[' name '), pathinfo_extension);
if (!in_array ($ext, $this->allowext)) {
$this->errormessage = ' unsupported file type ';
return false;
}

$this->fileext = $ext;
return true;;;
}

protected function Isvalidmimetype () {
$type = $this->fileinfos[' type '];

if (!in_array ($type, $this->allowmimetype)) {
$this->errormessage = ' Unsupported file MIME type ';
return false;
}

return true;
}

protected function Ishttppost () {
if (!is_uploaded_file ($this->fileinfos[' Tmp_name ')) {
$this->errormessage = ' file is not transmitted via HTTP POST ';

return false;
}

return true;
}

protected function Isrealimage () {
if ($this->isimageflag &&!getimagesize ($this->fileinfos[' Tmp_name ')) {
$this->errormessage = ' file is not a picture ';
return false;
}

return true;
}

protected function isuploadpathexist () {
if (!file_exists ($this->uploadpath)) {
mkdir ($this->uploadpath, 0777, true);
}
}

protected function Getuniquename () {
return MD5 (Microtime (TRUE), true);
}
}

$upload = new Upload (' myfile ');
if ($upload->uploadfile ()) {
echo "File upload success";
}

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.