Indefinite quantity form generation abbreviation is longer

Source: Internet
Author: User
Tags create directory error code explode file upload html form save file

Let's take a look at the example call method:

Effect Chart:

Let's look at the code. Upload class first? <?php


/*


Title:class Upload


FILE:class.upload.php


Description:to provide upload utility,


Author:peng Zhang zpadmin () gmail.com http://blog.neten.de


BASED on:whxbb whxbb () 21cn.com


writed:2005 NOV 20


modified:2006 MAR 01


Modify by Psdshow (Psdshow (at) yahoo.com.cn) 2007-11-30


Licence:gpl


revision:v1.0.2


*/


Class upload{


var $saveName;//Save Name


var $savePath;//save path


var $fileFormat = array (' gif ', ' jpg ', ' Doc ', ' Application/octet-stream ');//file Format &mime Limited


var $overwrite = 0;//Overlay mode


var $maxSize = 0;//file Maximum byte


var $ext;//File name extension


var $thumb = 0;//whether to generate thumbnails


var $thumbWidth = 130;//thumbnail width


var $thumbHeight = 130;//thumbnail height


var $thumbPrefix = "_thumb_";//thumbnail prefix


var $errno//Error code


var $returnArray = array ()//return information for all files


var $returninfo = array ()//File return information


Constructors
Save path @param $savePath file
@param $fileFormat file format limit array
Maximum size of @param $maxSize file
@param $overwriet overwrite 1 allow coverage 0 prohibit

function Upload ($savePath, $fileFormat = ', $maxSize = 0, $overwrite = 0) {
$this->setsavepath ($savePath);
$this->setfileformat ($fileFormat);
$this->setmaxsize ($maxSize);
$this->setoverwrite ($overwrite);
$this->setthumb ($this->thumb, $this->thumbwidth, $this->thumbheight);
$this->errno = 0;
}

Upload


@param $fileInput The name of the input in the page form (form)


@param $changeName whether to change the file name


function Run ($fileInput, $changeName = 1) {


if (Isset ($_files[$fileInput])) {


$FILEARR = $_files[$fileInput];


if (Is_array ($fileArr [' Name '])} {//Uploading the same file domain name multiple files


for ($i = 0; $i < count ($fileArr [' name ']); $i + +) {


$ar [' tmp_name '] = $fileArr [' Tmp_name '] [$i];


$ar [' name '] = $fileArr [' name '] [$i];


$ar [' type '] = $fileArr [' type '] [$i];


$ar [' size '] = $fileArr [' Size '] [$i];


$ar [' error '] = $FILEARR [' ERROR '] [$i];


$this->getext ($ar [' name ']);//Get extension, assign to $this->ext, and the next loop will update


$this->setsavename ($changeName = 1? ': $ar [' name ']);//Set Save file name


if ($this->copyfile ($ar)) {


$this->returnarray[] = $this->returninfo;


}else{


$this->returninfo[' ERROR '] = $this->errmsg ();


$this->returnarray[] = $this->returninfo;


}


}


Return $this->errno? False:true;


}else{//Upload a single file


$this->getext ($fileArr [' name ']);//Get extension


$this->setsavename ($changeName = 1? ': $fileArr [' name ']);//Set Save file name


if ($this->copyfile ($FILEARR)) {


$this->returnarray[] = $this->returninfo;


}else{


$this->returninfo[' ERROR '] = $this->errmsg ();


$this->returnarray[] = $this->returninfo;


}


Return $this->errno? False:true;


}


return false;


}else{


$this->errno = 10;


return false;


}


}

Single File Upload


@param array of $fileArray file information


function CopyFile ($fileArray) {


$this->returninfo = Array ();


return information


$this->returninfo[' name '] = $fileArray [' name '];


$this->returninfo[' savename '] = $this->savename;


$this->returninfo[' size '] = Number_format (($fileArray [' size '])/1024, 0, '. ', ');//KB


$this->returninfo[' type '] = $fileArray [' type '];


Check file format


if (! $this->validateformat ()) {


$this->errno = 11;


return false;


}


To check whether a directory is writable


if (! @is_writable ($this->savepath)) {


$this->errno = 12;


return false;


}


If overwriting is not allowed, check to see if the file already exists


if ($this->overwrite = = 0 && @file_exists ($this->savepath. $fileArray [' name ']) {


$this->errno = 13;


return false;


//}


If there is a size limit, check to see if the file exceeds the limit


if ($this->maxsize!= 0) {


if ($fileArray [size] > $this->maxsize) {


$this->errno = 14;


return false;


}


}


File Upload


if (! @move_uploaded_file ($fileArray ["Tmp_name"], $this->savepath. $this->savename)) {


$this->errno = $fileArray ["Error"];


return false;


}elseif ($this->thumb) {//create thumbnails


$CreateFunction = "Imagecreatefrom". ($this->ext = = ' jpg '? ' JPEG ': $this->ext);


$SaveFunction = "image". ($this->ext = = ' jpg '? ' JPEG ': $this->ext);


if (Strtolower ($CreateFunction) = = "Imagecreatefromgif"


&&!function_exists ("Imagecreatefromgif")) {


$this->errno = 16;


return false;


} elseif (Strtolower ($CreateFunction) = = "Imagecreatefromjpeg"


&&!function_exists ("Imagecreatefromjpeg")) {


$this->errno = 17;


return false;


} elseif (!function_exists ($CreateFunction)) {


$this->errno = 18;


return false;


}





$Original = @ $CreateFunction ($this->savepath. $this->savename);


if (! $Original) {$this->errno =; return false;}


$originalHeight = Imagesy ($Original);


$originalWidth = Imagesx ($Original);


$this->returninfo[' originalheight '] = $originalHeight;


$this->returninfo[' originalwidth '] = $originalWidth;


/*


if ($originalHeight < $this->thumbheight


&& $originalWidth < $this->thumbwidth)) {


If the thumbnail is smaller than expected, the copy


Move_uploaded_file ($this->savepath. $this->savename,


$this->savepath. $this->thumbprefix. $this->savename);


} else {


if ($originalWidth > $this->thumbwidth) {//width > Set width


$thumbWidth = $this->thumbwidth;


$thumbHeight = $this->thumbwidth * ($originalHeight/$originalWidth);


if ($thumbHeight > $this->thumbheight) {//high > Set height


$thumbWidth = $this->thumbheight * ($thumbWidth/$thumbHeight);


$thumbHeight = $this->thumbheight;


}


}elseif ($originalHeight > $this->thumbheight) {//high > Set height


$thumbHeight = $this->thumbheight;


$thumbWidth = $this->thumbheight * ($originalWidth/$originalHeight);


if ($thumbWidth > $this->thumbwidth) {//width > Set width


$thumbHeight = $this->thumbwidth * ($thumbHeight/$thumbWidth);


$thumbWidth = $this->thumbwidth;


}


}


*/


$radio =max (($originalWidth/$this->thumbwidth), ($originalHeight/$this->thumbheight));


$thumbWidth = (int) $originalWidth/$radio;


$thumbHeight = (int) $originalHeight/$radio;

if ($thumbWidth = = 0) $thumbWidth = 1;


if ($thumbHeight = = 0) $thumbHeight = 1;


$createdThumb = Imagecreatetruecolor ($thumbWidth, $thumbHeight);


if (! $createdThumb) {$this->errno = return false;}


if (!imagecopyresampled ($createdThumb, $Original, 0, 0, 0, 0,


$thumbWidth, $thumbHeight, $originalWidth, $originalHeight))


{$this->errno =; return false;}


if (! $SaveFunction ($createdThumb,


$this->savepath. $this->thumbprefix. $this->savename))


{$this->errno = return false;}





}


Delete temporary files


/*


if (!@ $this->del ($fileArray ["Tmp_name"])) {


return false;


}


*/


return true;


}

//file format checking, mime detection
 function Validateformat () {
  if (!is_array ($this->fileformat)
   | | In_array (Strtolower ($this->ext), $this->fileformat)
   | | In_array (Strtolower ($this-> returninfo[' type '], $this->fileformat))
   return true;
  else
    return false;
 }
//Get file extension
//@param $fileName the original filename of the uploaded file
 function getext ($fileName) {
   $ext = Explode (". ", $fileName);
   $ext = $ext [Count ($ext)-1];
   $this->ext = Strtolower ($ext);
 }

Set maximum byte limit for uploading files
@param $maxSize File Size (bytes) 0: Unrestricted
function Setmaxsize ($maxSize) {
$this->maxsize = $maxSize;
}
Set file format limits
@param $fileFormat array of file formats
function Setfileformat ($fileFormat) {
if (Is_array ($fileFormat)) {$this->fileformat = $fileFormat;}
}

Set Overlay mode
@param overwrite overwrite mode 1: Allow overlay 0: Prohibit overwrite
function Setoverwrite ($overwrite) {
$this->overwrite = $overwrite;
}


Set Save path
@param $savePath File Save path: End with "/" without "/", then fill
function Setsavepath ($savePath) {
$this->savepath = substr (Str_replace ("\", "/", $savePath),-1) = = "/"
? $savePath: $savePath. " /";
}

Set thumbnails
@param $thumb = 1 produces a thumbnail $thumbWidth, $thumbHeight is the width and height of the thumbnail
function Setthumb ($thumb, $thumbWidth = 0, $thumbHeight = 0) {
$this->thumb = $thumb;
if ($thumbWidth) $this->thumbwidth = $thumbWidth;
if ($thumbHeight) $this->thumbheight = $thumbHeight;
}

Set File Save name
@param $saveName Save name, if empty, the system automatically generates a random file name
function Setsavename ($saveName) {
if ($saveName = = ") {//If no filename is set, a random filename is generated
$name = Date (' Ymdhis '). " _ ". Rand (100,999). '. '. $this->ext;
To determine if a file exists and not allow duplicate files
if (file_exists ($this->savepath. $name)) {
$name = Setsavename ($saveName);
}
} else {
$name = $saveName;
}
$this->savename = $name;
}

deleting files
@param $fileName The file name you want to delete
Function del ($fileName) {
if (! @unlink ($fileName)) {
$this->errno = 15;
return false;
}
return true;
}

Return information on uploaded files
function GetInfo () {
return $this->returnarray;
}

Get error message


function ErrMsg () {


$uploadClassError = Array (


0 => ' There is no error, the file uploaded with success. ',


1 => ' The uploaded file exceeds the upload_max_filesize directive in php.ini. ',


2 => ' The uploaded file exceeds the max_file_size that is specified in the HTML form. '


3 => ' The uploaded file is only partially uploaded. ',


4 => ' No file was uploaded. ',


6 => ' Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3. ',


7 => ' Failed to write file to disk. Introduced in PHP 5.1.0. ',


=> ' Input name is not unavailable! ',


One => ' The uploaded file is unallowable! ',


=> ' Directory unwritable! ',


=> ' File exist already! ',


=> ' File is too big! ',


=> ' Delete file unsuccessfully! ',


=> ' Your version of PHP does not appear to have GIF thumbnailing. ',


=> ' Your version of PHP does not appear to have JPEG thumbnailing support. ',


=> ' Your version of PHP does not appear to have pictures thumbnailing. ',


=> ' An error occurred while attempting to copy the source image.


Your version of PHP ('. phpversion (). ') may isn't have this image type support. ',


=> ' An error occurred while attempting to create a new image. '


=> ' An error occurred while copying the source image to the thumbnail image. '


=> ' An error occurred while saving the thumbnail image to the filesystem.


Are you sure so PHP has been configured with both read and write access to this folder? '


);


if ($this->errno = = 0)


return false;


Else


return $uploadClassError [$this->errno];


}


}


?>

Let's see how it's called.:

<?php
If you receive the parameters from the form, upload processing, otherwise the form will be displayed
if (Isset ($_files[' uploadinput ')) {
Build the directory function, where the parameter $directoryname last No "/",
If so, when you break an array with '/', you end up with a null value
function Makedirectory ($directoryName) {
$directoryName = Str_replace ("\", "/", $directoryName);
$dirNames = explode ('/', $directoryName);
$total = count ($dirNames);
$temp = ';
for ($i =0; $i < $total; $i + +) {
$temp. = $dirNames [$i]. ' /';
if (!is_dir ($temp)) {
$oldmask = umask (0);
if (!mkdir ($temp, 0777)) exit ("Cannot create directory $temp");
Umask ($oldmask);
}
}
return true;
}

if ($_files[' uploadinput '] [' name '] &lt;&gt; ' ") {


Include Upload file class


Require_once (' class.upload.php ');


Set up file upload directory


$savePath = "Upload";


Create a table of contents


Makedirectory ($savePath);


Allowed file types


$fileFormat = Array (' gif ', ' jpg ', ' jpge ', ' png ');


File size limit, Unit: byte,1kb = 1000 Byte


0 means no limit, but is affected by upload_max_filesize settings in php.ini


$maxSize = 0;


Overwrite the original file? 0 does not allow 1 permission


$overwrite = 0;


Initialize Upload class


$f = new Upload ($savePath, $fileFormat, $maxSize, $overwrite);


If you want to generate a thumbnail, call the member function $f-&gt;setthumb ();


Parameter list: Setthumb ($thumb, $thumbWidth = 0, $thumbHeight = 0)


$thumb =1 indicates that the thumbnail is to be generated and is not invoked when the value is 0


$thumbWidth thumbnail width, in pixels (px), and left blank with default value 130


$thumbHeight thumbnail is high, in pixels (px), and left blank with the default value of 130


$f-&gt;setthumb (1);





The uploadinput in the parameter is the name of the input box for the upload file in the form


The following 0 indicates that the filename is not changed, and if 1, the system generates a random file name


if (! $f-&gt;run (' Uploadinput ', 1)) {


Only the last error message can be obtained through $f-&gt;errmsg (),


Detailed information is available in $f-&gt;getinfo ().


echo $f-&gt;errmsg (). &lt;br&gt;\n ";


}


The upload result is saved in the array ReturnArray.


echo "&lt;pre&gt;";


Print_r ($f-&gt;getinfo ());


echo "&lt;/pre&gt;";


}


}else{


?&gt;


&lt;form enctype= "Multipart/form-data" action= "" method= "POST" &gt;


Send this file: &lt;br/&gt;


&lt;input name= "uploadinput[]" type= "file" &gt;&lt;br/&gt;


&lt;input name= "uploadinput[]" type= "file" &gt;&lt;br/&gt;


&lt;input name= "uploadinput[]" type= "file" &gt;&lt;br/&gt;


&lt;input type= "Submit" value= "Send File" &gt;&lt;br/&gt;


&lt;/form&gt;


&lt;?php


}


We upload a picture file that already exists,


A normal picture file, and a file that is not allowed to upload,


The output is as follows


/*


The uploaded file is unallowable!

Array
(
    [0] => Array
        (
             [name] => boy.jpg
             [Savename] => boy.jpg
             [size] => 137
            [ Type] => image/pjpeg
            [ERROR] => File exist already!
       )

    [1] => Array
        (
             [name] => girl. JPG
            [savename] => girl. JPG
            [size] =>
             [Type] => image/pjpeg
             [originalheight] => 450
             [OriginalWidth] =>
       )

[2] => Array
(
[Name] => test.wma
[Savename] => test.wma
[Size] => 971
[Type] => audio/x-ms-wma
[ERROR] => the uploaded file is unallowable!
)

)
*/
?>

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.