文件上传是项目开发中比较常见的功能,但文件上传的过程比较繁琐,只要是有文件上传的地方就需要编写这些复杂的代码。为了能在每次开发中降低功能的编写难度,也为了能节省开发时间,通常我们都会将这些反复使用的一段代码封装到一个类中。
<?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程序设计有所帮助。

TOOPTIMIZEPHPCODEFORDUSEMEMORYUSAGEAGEAGEAGEAGEAGEANDEXECUTITIEM,关注台词:1)USEREEREFERESCENCENCINCOPYINSTEADOFCOPYINGINATATASTRUCTURESTROUCTURESTOREDUCEMORYCONSUMPTION.2)杠杆phphppphpphp'sbuilt intimpunctionslikearray_mapforfunctionslikearray_mapforfforfforfforfasterapasterexecution.3)

phpisusedforsendendemailsduetoitsignegrationwithservermailservicesand andexternalsmtpproviders,自动化notifications andMarketingCampaigns.1)设置设置yourphpenvironcormentswironmentswithaweberswithawebserverserverserverandphp,确保themailfunctionisenabled.2)useabasicscruct

发送电子邮件的最佳方法是使用PHPMailer库。1)使用mail()函数简单但不可靠,可能导致邮件进入垃圾邮件或无法送达。2)PHPMailer提供更好的控制和可靠性,支持HTML邮件、附件和SMTP认证。3)确保正确配置SMTP设置并使用加密(如STARTTLS或SSL/TLS)以增强安全性。4)对于大量邮件,考虑使用邮件队列系统来优化性能。

CustomHeadersheadersandAdvancedFeaturesInphpeMailenHanceFunctionalityAndreliability.1)CustomHeadersheadersheadersaddmetadatatatatataatafortrackingandCategorization.2)htmlemailsallowformattingandttinganditive.3)attachmentscanmentscanmentscanbesmentscanbestmentscanbesentscanbesentingslibrarieslibrarieslibrariesliblarikelikephpmailer.4)smtppapapairatienticationaltication enterticationallimpr

使用PHP和SMTP发送邮件可以通过PHPMailer库实现。1)安装并配置PHPMailer,2)设置SMTP服务器细节,3)定义邮件内容,4)发送邮件并处理错误。使用此方法可以确保邮件的可靠性和安全性。

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

使用依赖注入(DI)的原因是它促进了代码的松耦合、可测试性和可维护性。1)使用构造函数注入依赖,2)避免使用服务定位器,3)利用依赖注入容器管理依赖,4)通过注入依赖提高测试性,5)避免过度注入依赖,6)考虑DI对性能的影响。

phperformancetuningiscialbecapeitenhancesspeedandeffice,whatevitalforwebapplications.1)cachingwithapcureduccureducesdatabaseloadprovesrovesponsemetimes.2)优化


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

禅工作室 13.0.1
功能强大的PHP集成开发环境

DVWA
Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

VSCode Windows 64位 下载
微软推出的免费、功能强大的一款IDE编辑器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器
将Eclipse与SAP NetWeaver应用服务器集成。

PhpStorm Mac 版本
最新(2018.2.1 )专业的PHP集成开发工具