非常经典的PHP文件上传类分享_PHP
文件上传是项目开发中比较常见的功能,但文件上传的过程比较繁琐,只要是有文件上传的地方就需要编写这些复杂的代码。为了能在每次开发中降低功能的编写难度,也为了能节省开发时间,通常我们都会将这些反复使用的一段代码封装到一个类中。
<?php /** +----------------------------------------------------------------------------- * 文件上传类 +----------------------------------------------------------------------------- * @author Administrator +----------------------------------------------------------------------------- */ class FileUpload{ private $filepath; //保存路径 private $allowtype=array('gif','jpg','jpeg','png','txt'); private $maxsize=1000000; //最大允许上传大小 private $israndname=true; //是否随机 private $orginame; //原始文件名 private $tmpname; //临时文件名 private $newname; //新文件名 private $filetype; //文件类型 private $filesize; //文件大小 private $errornum=''; //错误号 private $errormsg; //错误信息 /** +------------------------------------------------------------------------------ *构造函数 +------------------------------------------------------------------------------ * @param string $savepath 保存路径 * @param string $allowtype 允许类型 * @param string $maxsize 允许大小 * +------------------------------------------------------------------------------ */ function __construct($option=array()){ foreach ($option as $key=>$value){ if (!in_array($key,get_class_vars(get_class($this)))){ continue; } $this->setOption($key, $value); } } function uploadfile($field) { $return=true; if (!$this->CheckPath()) { $this->errormsg=$this->geterrorNum(); return false; } $name=$_FILES[$field]['name']; $tmpname=$_FILES[$field]['tmp_name']; $filesize=$_FILES[$field]['size']; $error=$_FILES[$field]['error']; if (is_array($name)) { $errors=array(); for ($i=0;$i<count($name);$i++){ if ($this->getFile($name[$i],$tmpname[$i],$filesize[$i],$errors[$i])) { if (!$this->CheckSize() && !$this->CheckType()) { $errors=$this->getErrorNum(); return false; } }else{ $errors=$this->getErrorNum(); return false; } if (!$return) { $this->getFile(); } } if ($return) { $fileNames=array(); for ($i=0;$i<count($name);$i++){ if ($this->getFile($name[$i], $tmpname[$i], $filesize[$i], $filesize[$i])) { $this->SetFileName(); if (!$this->MoveFile()) { $errors[]=$this->getErrorNum(); $return=false; }else{ $fileNames[]=$this->getNewName(); } } } $this->newname=$fileNames; } $this->errormsg=$errors; return $return; }else{ if($this->getFile($name,$tmpname,filesize,$error)){ if(!$this->CheckSize()){ return false; } if(!$this->CheckType()){ return false; } $this->SetFileName(); if ($this->MoveFile()) { return true; } }else{ return false; } if (!$return) { $this->setOption('ErrorNum', 0); $this->errormsg=$this->geterrorNum(); } return $return; } } /** +------------------------------------------------------------------------ *设置类属性值函数 +------------------------------------------------------------------------ * @param mix $key * @param mix $value */ private function setOption($key,$value){ $key=strtolower($key); $this->$key=$value; } /** +--------------------------------------------------------------------------- * 获取文件变量参数函数 +--------------------------------------------------------------------------- * @param string $name * @param string $tmp_name * @param number $size * @param number $error */ private function getFile($name,$tmpname,$filetype,$filesize,$error=0){ $this->setOption('TmpName', $tmpname); $this->setOption('OrgiName', $name); $arrstr=explode('.', $name); $this->setOption('FileType', $arrstr[count($arrstr)-1]); $this->setOption('FileSize', $filesize); return true; } /** +------------------------------------------------------------------------- * 检查上传路径函数 +------------------------------------------------------------------------- * @return boolean */ private function CheckPath(){ if(empty($this->filepath)){ $this->setOption('ErrorNum', -5); return false; } if (!file_exists($this->filepath)||!is_writable($this->filepath)) { if (!@mkdir($this->filepath,0755)) { $this->setOption('ErrorNum',-4); return false; } } return true; } private function Is_Http_Post(){ if (!is_uploaded_file($this->tmpname)) { $this->setOption('ErrorNum',-6); return false; }else{ return true; } } /** +-------------------------------------------------------------------- *检查文件尺寸函数 +-------------------------------------------------------------------- * @return boolean */ private function CheckSize(){ if ($this->filesize>$this->maxsize) { $this->setOption('ErrorNum', -2); return false; }else{ return true; } } /** +--------------------------------------------------------------- * 检查文件类型函数 +--------------------------------------------------------------- * @return boolean */ private function CheckType(){ if (in_array($this->filetype, $this->allowtype)) { return true; }else{ $this->setOption('ErrorNum', -1); return false; } } private function SetFileName(){ if ($this->israndname) { $this->setOption('NewName', $this->RandName()); }else{ $this->setOption('NewName',$this->orginame); } } /** +----------------------------------------------------------------- * 获取新文件名 +------------------------------------------------------------------ */ public function getNewName() { return $this->newname; } private function RandName(){ $rule=date("YmdHis").rand(0, 999); return $rule.'.'.$this->filetype; } private function MoveFile(){ if ($this->errornum) { $filepath=rtrim($this->filaepath,'/').'/'; $filepath.=$this->newname; if (@move_uploaded_file($this->tmpname,$filepath)) { return true; }else{ $this->errormsg=$this->setOption('ErrorNum',-3 ); } }else{ return false; } } /** +---------------------------------------------------------------- * 错误信息函数 +---------------------------------------------------------------- * @return string */ function getErrorNum() { $erstr="上传文件<font color='red'>{$this->orginame}</font>出错"; switch ($this->errornum) { case 4: $erstr.="没有文件被上传"; break; case 3: $erstr.="文件只被部分上传"; break; case 2: $erstr.="上传文件超过了HTML表单MAX_FILE_SIZE指定的值"; break; case 1: $erstr.="上传文件超过了php.ini配置文件中upload_max_filesize的值"; break; case 0: $erstr="上传{$this->orginame}成功"; break; case -1: $erstr="未允许的类型"; break; case -2: $erstr.="文件过大,不能超过{$this->maxsize}个字节"; break; case -3: $erstr.="上传失败"; break; case -4: $erstr="创建上传目录失败,请重新指定上传目录"; break; case -5: $erstr="未指定上传路径"; break; case -6: $erstr="非法操作"; break; default: $erstr.="未知错误"; } return $erstr; } } ?>
以上就是本文的全部内容,希望对大家学习php程序设计有所帮助。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

In PHPOOP, self:: refers to the current class, parent:: refers to the parent class, static:: is used for late static binding. 1.self:: is used for static method and constant calls, but does not support late static binding. 2.parent:: is used for subclasses to call parent class methods, and private methods cannot be accessed. 3.static:: supports late static binding, suitable for inheritance and polymorphism, but may affect the readability of the code.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

HTTP request methods include GET, POST, PUT and DELETE, which are used to obtain, submit, update and delete resources respectively. 1. The GET method is used to obtain resources and is suitable for read operations. 2. The POST method is used to submit data and is often used to create new resources. 3. The PUT method is used to update resources and is suitable for complete updates. 4. The DELETE method is used to delete resources and is suitable for deletion operations.

PHP handles file uploads through the $\_FILES variable. The methods to ensure security include: 1. Check upload errors, 2. Verify file type and size, 3. Prevent file overwriting, 4. Move files to a permanent storage location.

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.
