1<?PHP2 3 /**4 * Implement file Upload5 * Five information @param array $file uploaded files6 * @param array $allow type of file upload allowed7 * @param string & $error used to log error messages8 * Upload directory @param string $part file9 * @param int $maxsize = 1048576Ten * @return Mixed false| $nwename failure returns false, the new name is returned successfully One */ A - functionUpload$file,$allow,&$error,$path,$maxsize=1048576){ - //1, first judge the system error the Switch($file[' Error ']){ - Case1:$error= "Upload failed, beyond the limit of file size!" "; - return false; - Case2:$error= "Upload failed, exceeding file size allowed by browser form!" "; + return false; - Case5 |$error= "Upload failed, file upload is not complete!" "; + return false; A Case4:$error= "Upload failed, please first select the file to upload!" "; at return false; - Case6: - Case7:$error= "Sorry, the server is busy, please try again later!" "; - return false; - } - in //2 Validation Logic Error--File size - if($file[' Size '] >$maxsize){ to $error= "Upload failed, beyond the limit of file size!" "; + return false; - } the * //File Type $ if(!In_array($file[' type '],$allow)){Panax Notoginseng $error= "The upload file type is incorrect, the allowed types are:".implode(‘,‘,$allow); - return false; the } + //3. Move Temporary files A //3.1 get a new name for the file the $newname= Randname ($file[' Name ']); + //3.2 Determining the file storage path - $target=$path. ‘/‘ .$newname; $ //3.3 Start Moving $ $result=Move_uploaded_file($file[' Tmp_name '],$target); - if($result){ - //Upload Successful the return $newname; -}Else{Wuyi //Upload failed the $error= "An unknown error occurred and the upload failed!" "; - return false; Wu } - } About $ /** - * Generate a random name function = Current timestamp + randomly generated character - * @param string $filename The original name of the file - * @return A new name for string $newname file A * + */ the - functionRandname ($filename){ $ //1, generating the timestamp portion of the file name the $newname=Date("Ymdhis"); the //2, plus a few random numbers. the $str= "1234567890"; the for($i= 0;$i<6;$i++){ - $newname.=$str[Mt_rand(0,strlen($str)-1)]; in } the //3, plus the suffix name of the file the $newname.=STRRCHR($filename,‘.‘); About return $newname; the}
Encapsulates a file upload and detect security, rename script