PHP File Upload class

Source: Internet
Author: User
Tags php file upload

<?php
/**
file:fileupload.class.php File Upload class FileUpload
The instance object of this class is used to process the uploaded file, can upload a file, and can handle multiple file uploads at the same time.
*/
Class FileUpload {
Private $path = "./uploads"; Upload File Save path
Private $allowtype = array (' jpg ', ' gif ', ' PNG '); Set the type of limit upload file
Private $maxsize = 1000000; Limit file Upload size (bytes)
Private $israndname = true; Sets whether to randomly rename files, false not random

Private $originName; Source file name
Private $tmpFileName; Temporary file name
Private $fileType; File type (file suffix)
Private $fileSize; File size
Private $newFileName; New file name
Private $errorNum = 0; Error number
Private $errorMess = ""; Error Reporting messages

/**
* For setting member properties ($path, $allowtype, $maxsize, $israndname)
* Multiple property values can be set at once through a coherent operation
* @param string $key member property name (case insensitive)
* @param mixed $val The value set for the member property
* @return Object returns its own $this, which can be used for coherent operation
*/
function set ($key, $val) {
$key = Strtolower ($key);
if (Array_key_exists ($key, Get_class_vars (Get_class ($this)))) {
$this->setoption ($key, $val);
}
return $this;
}

/**
* Call this method to upload a file
* @param string $fileFile The name of the form that uploaded the file
* @return BOOL If the upload succeeds returns the number true
*/

function upload ($fileField) {
$return = true;
/* Check the file path is a legal delay */
if (! $this->checkfilepath ()) {
$this->errormess = $this->geterror ();
return false;
}
/* Take out the file upload information to the variable */
$name = $_files[$fileField [' name '];
$tmp _name = $_files[$fileField] [' tmp_name '];
$size = $_files[$fileField [' size '];
$error = $_files[$fileField] [' ERROR '];

/* If multiple files are uploaded, $file["name"] will be an array */
if (Is_array ($name)) {
$errors =array ();
/* Multiple file uploads are recycled, this loop only checks the upload file's role, and does not actually upload */
for ($i = 0; $i < count ($name); $i + +) {
/* Set File information */
if ($this->setfiles ($name [$i], $tmp _name[$i], $size [$i], $error [$i]) {
if (! $this->checkfilesize () | |! $this->checkfiletype ()) {
$errors [] = $this->geterror ();
$return =false;
}
}else{
$errors [] = $this->geterror ();
$return =false;
}
/* If there is a problem, re-start the attribute */
if (! $return)
$this->setfiles ();
}

if ($return) {
/* Keep a variable array of all uploaded file names */
$fileNames = Array ();
/* If multiple uploaded files are legitimate, upload files to the server via Ecstasy loop */
for ($i = 0; $i < count ($name); $i + +) {
if ($this->setfiles ($name [$i], $tmp _name[$i], $size [$i], $error [$i]) {
$this->setnewfilename ();
if (! $this->copyfile ()) {
$errors [] = $this->geterror ();
$return = false;
}
$fileNames [] = $this->newfilename;
}
}
$this->newfilename = $fileNames;
}
$this->errormess = $errors;
return $return;
/* Upload a Single file processing method */
} else {
/* Set File information */
if ($this->setfiles ($name, $tmp _name, $size, $error)) {
/* Check the size and type before uploading */
if ($this->checkfilesize () && $this->checkfiletype ()) {
/* Set a new filename for the upload file */
$this->setnewfilename ();
/* Upload file returns 0 for success, less than 0 for error */
if ($this->copyfile ()) {
return true;
}else{
$return =false;
}
}else{
$return =false;
}
} else {
$return =false;
}
Error if $return is false, save error message in property errormess
if (! $return)
$this->errormess= $this->geterror ();

return $return;
}
}

/**
* Get the file name after uploading
* @param void No parameters
* @return string after uploading, the name of the new file, if it is multiple file upload return array
*/
Public Function GetFileName () {
return $this->newfilename;
}

/**
* After the upload failed, call the method to return, upload error message
* @param void No parameters
* @return String Returns the information report of error uploading file, if it is multiple file upload return array
*/
Public Function geterrormsg () {
return $this->errormess;
}

/* Set upload error message */
Private Function GetError () {
$STR = "Error uploading file <font color= ' red ' >{$this->originname}</font>:";
Switch ($this->errornum) {
Case 4: $str. = "No files are uploaded"; Break
Case 3: $str. = "file is only partially uploaded"; Break
Case 2: $str. = "The size of the uploaded file exceeds the value specified by the MAX_FILE_SIZE option in the HTML form"; Break
Case 1: $str. = "The uploaded file exceeds the value of the Upload_max_filesize option limit in php.ini"; Break
Case-1: $str. = "type not allowed"; Break
Case-2: $str. = "File is too large, the uploaded file cannot exceed {$this->maxsize} bytes"; Break
Case-3: $str. = "Upload Failed"; Break
Case-4: $str. = "Failed to set up the directory to upload files, please re-specify the upload directory"; Break
Case-5: $str. = "The path of the uploaded file must be specified"; Break
Default: $str. = "Unknown error";
}
return $str. ' <br> ';
}

/* Set and $_files related content */
Private Function setfiles ($name = "", $tmp _name= "", $size =0, $error =0) {
$this->setoption (' ErrorNum ', $error);
if ($error)
return false;
$this->setoption (' Originname ', $name);
$this->setoption (' Tmpfilename ', $tmp _name);
$ARYSTR = Explode (".", $name);
$this->setoption (' FileType ', Strtolower ($aryStr [Count ($ARYSTR)-1]));
$this->setoption (' fileSize ', $size);
return true;
}

/* Set values for individual member properties */
Private Function SetOption ($key, $val) {
$this $key = $val;
}

/* Set the file name after upload */
Private Function Setnewfilename () {
if ($this->israndname) {
$this->setoption (' NewFileName ', $this->prorandname ());
} else{
$this->setoption (' NewFileName ', $this->originname);
}
}

/* Check if the uploaded file is of a valid type */
Private Function Checkfiletype () {
if (In_array (Strtolower ($this->filetype), $this->allowtype)) {
return true;
}else {
$this->setoption (' ErrorNum ',-1);
return false;
}
}

/* Check if the uploaded file is the allowed size */
Private Function Checkfilesize () {
if ($this->filesize > $this->maxsize) {
$this->setoption (' ErrorNum ',-2);
return false;
}else{
return true;
}
}

/* Check if there is a directory for uploading files */
Private Function Checkfilepath () {
if (Empty ($this->path)) {
$this->setoption (' ErrorNum ',-5);
return false;
}
if (!file_exists ($this->path) | |!is_writable ($this->path)) {
if ([email protected] ($this->path, 0755)) {
$this->setoption (' ErrorNum ',-4);
return false;
}
}
return true;
}

/* Set Random file name */
Private Function Prorandname () {
$fileName = Date (' Ymdhis '). " _ ". Rand (100,999);
Return $fileName. '. '. $this->filetype;
}

/* Copy the upload file to the specified location */
Private Function CopyFile () {
if (! $this->errornum) {
$path = RTrim ($this->path, '/'). ' /‘;
$path. = $this->newfilename;
if (@move_uploaded_file ($this->tmpfilename, $path)) {
return true;
}else{
$this->setoption (' ErrorNum ',-3);
return false;
}
} else {
return false;
}
}
}

<?php
Contains an upload class in a file upload class
Include "fileupload.class.php";

$up = new FileUpload;
Set properties (upload location, size, type, and whether the name is to be randomly generated)
$up, set ("Path", "./images/");
$up, set ("MaxSize", 2000000);
$up, set ("Allowtype", Array ("GIF", "png", "JPG", "jpeg"));
$up, set ("Israndname", false);

Using the Upload method in the object, you can upload the file, the method needs to pass an upload form the name of the PIC, if successful returns TRUE, the failure returns false
if ($up-Upload ("pic")) {
Echo ' <pre> ';
Get file name after upload
Var_dump ($up->getfilename ());
Echo ' </pre> ';

} else {
Echo ' <pre> ';
Get an error message after uploading failed
Var_dump ($up->geterrormsg ());
Echo ' </pre> ';
}
?>

<form action= "upload.php" method= "post" enctype= "Multipart/form-data" >
Name: <input type= "text" name= "username" value= "/><br>
<input type= "hidden" name= "max_file_size" value= "1000000"/>
Up Pic: <input type= "file" name= "pic[" "value=" "><br>
Up Pic: <input type= "file" name= "pic[" "value=" "><br>
Up Pic: <input type= "file" name= "pic[" "value=" "><br>
Up Pic: <input type= "file" name= "pic[" "value=" "><br>

<input type= "Submit" value= "Upload"/><br>

</form>

PHP File Upload class

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.