多文件上传 多文件上传 php 原生程序
php文件上传(详细方法)

<?php/***文件的上传:*1.单个文件上传*2.多个文件上传*一、php配置文件中和上传有关的配置选项【经测试,修改配置文件修改的是wamp下的apache下的php.ini】*php.ini里面*file_uploads=on是必须的,不然文件写得再对都上传不到服务器上。
*upload_max_filesize=20M这个值一定不要超过服务器的内存大小。
*post_max_size=250M这个值是post的最大值,一定要比上传文件的最大值要大。
*上传上去的数据临时存在什么地方?upload_tmp_dir=c:/uploads/*在脚本执行完以后,临时文件会删除,所以在脚本执行完以前一定要把你上传的文件copy出来,不然就没了。
**二、上传需要注意的事项*文件上传表单需要注意什么?* 1.如果有文件上传操作,表单的提交方法method=post,必须用post。
* 2.表单上传需要使用类型为file的input* 3.enctype="multipart/form-data"只有文件上传时才用这个,用来指定表单编码的数据方式。
让服务器知道我们要传递文件。
*并带有一些常规的信息。
加在form里面和method一样。
*三、php处理上传的数据*$_POST提取post方法提交的的表单数据,如果是文件上传的数据则使用$_FILES接收文件,而$_POST接收*非文件数据。
所以当要上传文件时用两种方法接收数据。
点击上传后只要将临时文件移动到目标文件夹中就成功了。
*array(size=4)'shopname'=>string'得到'(length=6)'shoppri'=>string'得到'(length=6)'shopnum'=>string'得到'(length=6)'sub'=>string'添加商品'(length=12)array(size=1)'pic'=>array(size=5)'name'=>string'11112907_124211588000_2[1].jpg' (length=30)'type'=>string'image/jpeg'(length=10)'tmp_name'=>string'D:\wamp\tmp\phpDAA.tmp' (length=22)'error'=>int0'size'=>int288127**/header("Content-Type:text/html;charset=utf-8");date_default_timezone_set("PRC");//设置时区if(isset($_POST["sub"])){//var_dump($_POST);//var_dump(__FILE__);//string'D:\wamp\www\mytest\10-29-fileupload01.php'(length=41)//var_dump($_FILES);/*点击上传之后,执行以下操作*///1.使用$_FILES["pic"]["error"]检查错误if($_FILES['pic']['error']>0){switch($_FILES['pic']['error']){case1:echo"上传的文件超过了php.ini中upload_max_filesize选项限制的值<br/>";break;case2:echo"文件大小超过了1M<br/>";break;case3:echo"文件只有部分被上传<br/>";break;case4:echo"没有文件被上传<br/>";break;default:echo"未知错误<br/>";}exit;}//2.使用$_FILES["pic"]["size"]限制大小if($_FILES['pic']['size']>1000000){echo"文件不能大于1M<br/>";exit;}//3.使用$_FILES["pic"]["type"]或文件的扩展名来限制类型。
PHP文件上传-通过类实现单文件或多文件上传

PHP⽂件上传-通过类实现单⽂件或多⽂件上传本案例有三个⽂件,⽬录结构如下图:核⼼⽂件上传类uploads.class.php (既能上传单⽂件⼜能上传多⽂件),程序不⾜之处还请多多指教!uploads.class.php代码如下:<?phpclass uploads{protected$fileName;protected$maxSize;protected$allowMime;protected$allowExt;protected$uploadPath;protected$imgFlag;protected$fileInfo;protected$error;protected$ext;protected$uniName;protected$destination;protected$file;protected$files;protected$i;protected$key;protected$value;protected$res;protected$uploadFiles;public function __construct($uploadPath='./uploads',$imgFlag=true,$maxSize=5242880,$allowExt=array('jpeg','jpg','png','gif'),$allowMime=array('image/jpeg','image/png','image/gif')){ //$this->fileName=$fileName;$this->maxSize=$maxSize;$this->allowMime=$allowMime;$this->allowExt=$allowExt;$this->uploadPath=$uploadPath;$this->imgFlag=$imgFlag;//$this->fileInfo=$_FILES[$this->fileName];//构建上传⽂件的信息foreach($_FILES as$this->file){if(is_string($this->file['name'])){$this->files[$this->i]=$this->file;$this->i++;}elseif(is_array($this->file['name'])){foreach($this->file['name'] as$this->key=>$this->value){$this->files[$this->i]['name']=$this->file['name'][$this->key];$this->files[$this->i]['type']=$this->file['type'][$this->key];$this->files[$this->i]['tmp_name']=$this->file['tmp_name'][$this->key];$this->files[$this->i]['error']=$this->file['error'][$this->key];$this->files[$this->i]['size']=$this->file['size'][$this->key];$this->i++;}}}}protected function checkError(){if($this->fileInfo['error']!=0){switch($this->fileInfo['error']){case 1:$this->error='上传⽂件超出了php配置中upload_max_filesize选项的值';break;case 2:$this->error="超出了表单MAX_FILE_SIZE限制的⼤⼩";break;case 3:$this->error="⽂件部分被上传";break;case 4:$this->error="没有选择上传⽂件";break;case 6:$this->error="没找到临时⽬录";break;case 7:$this->error="⽂件不可写";break;case 8:$this->error="系统错误";break;}return false;}return true;}protected function checkExt(){$this->ext=strtolower(pathinfo($this->fileInfo['name'],PATHINFO_EXTENSION));if(!in_array($this->ext,$this->allowExt)){$this->error='不允许的扩展名';return false;}return true;}protected function checkSize(){if($this->fileInfo['size']>$this->maxSize){$this->error='上传⽂件过⼤';return false;}return true;}/*检测⽂件类型的*/protected function checkMime(){if(!in_array($this->fileInfo['type'],$this->allowMime)){$this->error='不允许的⽂件类型';return false;}return true;}protected function checkTrueImg(){if($this->imgFlag){if(!@getimagesize($this->fileInfo['tmp_name'])){$this->error='不是真实图⽚';return false;}}return true;}/*是否通过HTTPPOST⽅式上传上来的*/protected function checkHTTPPOST(){if(!is_uploaded_file($this->fileInfo['tmp_name'])){$this->error='⽂件不是通过HTTPPOST⽅式上传上来的';return false;}return true;}/*显⽰错误信息*/protected function showError(){echo('<sapn style="color:red;">'.$this->error.'</sapn>');echo "<br/>";}protected function checkUploadPath(){if(!file_exists($this->uploadPath))mkdir($this->uploadPath,0777,true);}/*产⽣唯⼀字符串*/protected function getUniName(){return md5(uniqid(microtime(true),true));}protected function uploadFile(){if($this->checkError()&&$this->checkExt()&&$this->checkSize()&&$this->checkMime()&&$this->checkTrueImg()&&$this->checkHTTPPOST()){ $this->checkUploadPath();$this->uniName=$this->getUniName();$this->destination=$this->uploadPath.'/'.$this->uniName.'.'.$this->ext; if(@move_uploaded_file($this->fileInfo['tmp_name'],$this->destination)){ $this->uploadFiles[]=$this->destination;}else{$this->error='⽂件移动失败';$this->showError();}}else{$this->showError();}}public function uploadsFile(){foreach($this->files as$this->fileInfo){$this->uploadFile($this->fileInfo);}return$this->uploadFiles;}}upload3.html⽂件代码如下:<html><head><meta charset="utf-8"></head><body><form action="do_action3.php" method="post"enctype="multipart/form-data"><!--<input type="hidden" name="MAX_FILE_SIZE" value="176942">--><label for="file">请选择要上传的⽂件:</label><input type="file" name="file1" id="file"/><br /><label for="file">请选择要上传的⽂件:</label><input type="file" name="file2" id="file"/><br /><label for="file">请选择要上传的⽂件:</label><input type="file" name="file[]" id="file"/><br /><label for="file">请选择要上传的⽂件:</label><input type="file" name="file[]" id="file"/><br /><label for="file">请选择要上传的⽂件:</label><input type="file" name="file[]" id="file" multiple /><br /> <input type="submit" name="submit" value="上传"/></form></body></html>do_action3.php⽂件的代码如下:<?phpheader("content-type:text/html;charset=utf-8");//header("content-type:text/html;charset=utf-8;");require_once "uploads.class.php";echo "<pre>";$upload=new uploads();$dest=$upload->uploadsFile();var_dump($dest);测试截图如有疑问加QQ群联系我!。
php 实现多文件上传程序代码

php 实现多文件上传程序代码php文件上传与多文件上传其它没有多大的区别,多文件上传只是我们把表单名改成数组形式,而获取利用foreach遍历就可以实现多文件上传了,动态多文件上传只要在js加一个动态增加多文件上传框,同样在php处理时就遍历一下数组就成了。
最简单的实例如下代码如下复制代码<form action="" method="post" enctype="multipart/form-data"><p>Pictures:<input type="file" name="pictures[]" /><input type="file" name="pictures[]" /><input type="file" name="pictures[]" /><input type="submit" value="Send" /></p></form><?phpforeach ($_FILES["pictures"]["error"] as $key => $error) {if ($error == UPLOAD_ERR_OK) {$tmp_name = $_FILES["pictures"]["tmp_name"][$key];$name = $_FILES["pictures"]["name"][$key];move_uploaded_file($tmp_name, "data/$name");}}?>下面分享其它朋友的例子例1代码如下复制代码<?//filename:multi_upload.phpif($ifupload){$path=AddSlashes(dirname($PATH_TRANSLATED))."upload";for($i=1;$i<=8;$i++){$files="afile".$i;if(${$files}!="none"){if(copy(${$files},$path.${$files."_name"})){}}}print "<b>You have uploaded files successfully</b><br>";print "<a href="multi_upload.php">Return</a>";exit;}?><html><html><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312"> <meta NAME="GENERATOR" Content="Microsoft Visual Studio 6.0"> <title>多个文件上传</title><style type="text/css"><!--BODY{PADDING-RIGHT: 0px;MARGIN-TOP: 0px;PADDING-LEFT: 0px;FONT-SIZE: 8px;MARGIN-LEFT: 0px;CURSOR: default;COLOR: black;MARGIN-RIGHT: 0px;PADDING-TOP: 0px;FONT-FAMILY: Arial; BACKGROUND-COLOR: transparent; TEXT-ALIGN: center}.TxtInput{FONT-SIZE: 8pt;WIDTH: 100%;CURSOR: default;COLOR: black;FONT-FAMILY: Arial;HEIGHT: 21px;BACKGROUND-COLOR: white; TEXT-ALIGN: left}.FieldLabel{FONT-WEIGHT: normal;FONT-SIZE: 9pt;WIDTH: 100%;COLOR: black;FONT-FAMILY: Arial; BACKGROUND-COLOR: transparent; TEXT-ALIGN: left}.HeadBtn{BORDER-RIGHT: black 1px solid; BORDER-TOP: white 1px solid; FONT-SIZE: 8pt;OVERFLOW: hidden;BORDER-LEFT: white 1px solid; WIDTH: 70px;COLOR: black;BORDER-BOTTOM: black 1px solid; FONT-FAMILY: Arial;HEIGHT: 21px;BACKGROUND-COLOR: #8e8dcd; TEXT-ALIGN: center}.TransEx{BORDER-RIGHT: black 1px solid; PADDING-RIGHT: 8px;BORDER-TOP: white 1px solid; PADDING-LEFT: 8px;FONT-SIZE: 8pt;PADDING-BOTTOM: 3px;BORDER-LEFT: white 1px solid; WIDTH: 720px;PADDING-TOP: 3px;BORDER-BOTTOM: black 1px solid;FONT-FAMILY: Arial;BACKGROUND-COLOR: #c0c0c0;TEXT-ALIGN: center}--></style><script language="javascript">function window.onload(){document.forms[0].btnOk.onclick=btn_ok;}function btn_ok(){for(var i=1;i<=8;i++){if(eval("document.forms[0].afile"+i+".value!=''"))document.forms[0].submit();return true;}alert("None of file have been select ed");return false;}</script></head><body><form method="post" action="multi_upload.php" name="frmUpload" enctype="multipart/form-data" ><table id="divContainer" style="HEIGHT: 100%; WIDTH: 380" border="0"> <tr height="35"><td align="right" valign="bottom">多文件上传</td></tr><tr><td align="center" valign="top"><table class="Transex" border="0" cellspacing="0" cellpadding="0" style="WIDTH: 360px"><tr style="HEIGHT: 10px" ><td style="WIDTH: 5px"></td><td colspan="2"></td><td style="WIDTH: 5px"></td></tr><tr><td></td><td nowrap><label class="FieldLabel"> 文件1</label></td><td><input type="file" class="TxtInput" tabindex="1" name="afile1" style="WIDTH: 282px"></td> <td></td></tr><tr><td></td><td nowrap><label class="FieldLabel"> 文件2</label></td><td><input type="file" class="TxtInput" tabindex="2" name="afile2" style="WIDTH: 282px"></td> <td></td></tr><tr><td></td><td nowrap><label class="FieldLabel"> 文件3</label></td><td><input type="file" class="TxtInput" tabindex="3" name="afile3" style="WIDTH: 282px"></td> <td></td></tr><tr><td></td><td nowrap><label class="FieldLabel"> 文件4</label></td><td><input type="file" class="TxtInput" tabindex="4" name="afile4" style="WIDTH: 282px"></td> <td></td></tr><tr><td></td><td nowrap><label class="FieldLabel"> 文件5</label></td><td><input type="file" class="TxtInput" tabindex="5" name="afile5" style="WIDTH: 282px"></td> <td></td></tr><tr><td></td><td nowrap><label class="FieldLabel"> 文件6</label></td><td><input type="file" class="TxtInput" tabindex="6" name="afile6" style="WIDTH: 282px"></td> <td></td></tr><tr><td></td><td nowrap><label class="FieldLabel"> 文件7</label></td><td><input type="file" class="TxtInput" tabindex="7" name="afile7" style="WIDTH: 282px"></td> <td></td></tr><tr><td></td><td nowrap><label class="FieldLabel"> 文件8</label></td><td><input type="file" class="TxtInput" tabindex="8" name="afile8" style="WIDTH: 282px"></td> <td></td></tr><tr style="HEIGHT: 5px"><td style="WIDTH: 5px"><td style="WIDTH: 350px" colspan="2"><hr width="100%"></td><td style="WIDTH: 5px"></td></tr><tr><td></td><td colspan="2" align="left"><button tabindex="5" class="headbtn" align="center" name="btnOk" id="btnOk" accesskey="O">确定(<ins>O</ins>)</button><input type="hidden" name="ifupload" value=1><button tabindex="5" class="eadbtn" align="center" name="btnCancel"id="btnCancel" accesskey="C" onclick="window.close();">取消(<ins>C</ins>)</button></td><td></td></tr><tr style="HEIGHT: 5px"><td style="WIDTH: 5px"><td style="WIDTH: 350px" colspan="2"></td><td style="WIDTH: 5px"></td></tr></table></td></tr></table></form></body></html>如果我们要动态不确定性的多文件上传怎么实现下面也有实例文件上传代码代码如下复制代码view plaincopy to clipboardprint?<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312" /><title>文档上传</title></head><body><script language="javascript"><!--动态添加文件选择控件-->function AddRow(){var eNewRow = tblData.insertRow();for (var i=0;i<1;i++){var eNewCell = eNewRow.insertCell();eNewCell.innerHTML = "<tr><td><input type='file' name='filelist[]' size='50'/></td></tr>";}}// --></script><form name="myform" method="post" action="uploadfile.php" enctype="multipart/form-data" > <table id="tblData" width="400" border="0"><!-- 将上传文件必须用post的方法和enctype="multipart/form-data" --><!-- 将本页的网址传给uploadfile.php--><input name="postadd" type="hidden" value="<?php echo"http://".$_SERVER['HTTP_HOST'].$_SERVER["PHP_SELF"]; ?>" /><tr><td>文件上传列表<input type="button" name="addfile" onclick="AddRow()" value="添加列表" /></td></tr><!-- filelist[]必须是一个数组--><tr><td><input type="file" name="filelist[]" size="50" /></td></tr></table><input type="submit" name="submitfile" value="提交文件" /></form></body></html><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312" /><title>文档上传</title></head><body><script language="javascript"><!--动态添加文件选择控件-->function AddRow(){var eNewRow = tblData.insertRow();for (var i=0;i<1;i++){var eNewCell = eNewRow.insertCell();eNewCell.innerHTML = "<tr><td><input type='file' name='filelist[]' size='50'/></td></tr>";}}// --></script><form name="myform" method="post" action="uploadfile.php" enctype="multipart/form-data" > <table id="tblData" width="400" border="0"><!-- 将上传文件必须用post的方法和enctype="multipart/form-data" --><!-- 将本页的网址传给uploadfile.php--><input name="postadd" type="hidden" value="<?php echo"http://".$_SERVER['HTTP_HOST'].$_SERVER["PHP_SELF"]; ?>" /><tr><td>文件上传列表<input type="button" name="addfile" onclick="AddRow()" value="添加列表" /></td></tr> <!-- filelist[]必须是一个数组--><tr><td><input type="file" name="filelist[]" size="50" /></td></tr></table><input type="submit" name="submitfile" value="提交文件" /></form></body></html>提交文件代码view plaincopy to clipboardprint?<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312" /><title>文件上传结果</title></head><body><?phpif ($_POST["submitfile"]!=""){$Path="./".date('Ym')."/";if (!is_dir($Path))//创建路径{ mkdir($Path); }echo "<div>";for ($i=0;$i<count($filelist);$i++){ //$_FILES["filelist"]["size"][$i]的排列顺序不可以变,因为fileist是一个二维数组if ($_FILES["filelist"]["size"][$i]!=0){$File=$Path.date('Ymdhm')."_".$_FILES["filelist"]["name"][$i];if (move_uploaded_file($_FILES["filelist"]["tmp_name"][$i],$File)){ echo "文件上传成功文件类型:".$_FILES["filelist"]["type"][$i]." "."文件名:".$_FILES["filelist"]["name"][$i]."<br>"; }else{ echo "文件名:".$_FILES["filelist"]["name"][$i]."上传失败</br>"; }}}echo "</div><br><a href="$postadd" href="$postadd">返回</a></div>";}?></body></html>另:错误信息说明从PHP 4.2.0 开始,PHP 将随文件信息数组一起返回一个对应的错误代码。
PHP文件批量上传类

class upFiles{/*** 上传的文件信息* @var array*/public $uploadFiles = array();/*** 保存文件路径* @var string*/public $saveFilePath;/*** 最大文件大小* @var int*/public $maxFileSize;/*** 错误信息* @var string*/public $lastError;/*** 默认充许上传的文件类型* @var array*/public $allowType = array('gif','jpg','png','bmp');/*** 最终保存的文件名称* @var string*/public $finalFilePath;/*** 返回已经上传文件的详细信息* @var array*/public $saveFileInfo = array();/*** 构造函数,初始化相关信息,包括文件内容,上传地址,文件最大限制,文件类型* @param array $file* @param string $path* @param int $size* @param array $typepublic function __construct($file,$path,$size= 2097152,$type = ''){$this->uploadFiles = $file;$this->saveFilePath = $path;$this->maxFileSize = $size;if($type != '') $this->allowType = $type;}public function upload(){for($i=0;$i<count($this->uploadFiles['name']);$i++){//如果文件上传没有出现错误if($this->uploadFiles['error'][$i] == 0){//获取当前文件名,临时文件名,文件大小,扩展名$name = $this->uploadFiles['name'][$i];$tmpname = $this->uploadFiles['tmp_name'][$i];$size = $this->uploadFiles['size'][$i];$minetype = $this->uploadFiles['type'][$i];$type = $this->getFileExt($this->uploadFiles['name'][$i]);//检查文件大小是否合法if(!$this->checkSize($size)){$this->lastError = "文件大小超出限制.文件名称:".$name;$this->printMsg($this->lastError);continue;}//检查文件扩展名是否合法if(!$this->checkType($type)){$this->lastError = "非法的文件类型.文件名称:".$name;$this->printMsg($this->lastError);continue;}//检测当前文件是否非法提交if(!is_uploaded_file($tmpname)){$this->lastError = "上传文件无效.文件名称:".$name;$this->printMsg($this->lastError);continue;}//移动后的文件名称$basename = $this->getBaseName($name,'.'.$type);//上传文件重新命名,格式为UNIX时间戳+4位随机数,生成一个14位文件名$savename = time().mt_rand(1000,9999).'.'.$type;//创建上传文件的文件夹@mkdir($this->saveFilePath);$file_name1 = $this->saveFilePath.'/'.date('Y');@mkdir($file_name1);$file_name2 = $this->saveFilePath.'/'.date('Y').'/'.date('m');@mkdir($file_name2);//最终组合的文件路径$this->finalFilePath = $file_name2.'/'.$savename;//把上传的文件从临时目录移到目标目录if(!move_uploaded_file($tmpname,$this->finalFilePath)){$this->$this->uploadFiles['error'][$i];$this->printMsg($this->lastError);continue;}//存储已经上传的文件信息$this->saveFileInfo = array('name' => $name,'type' => $type,'minetype' => $minetype,'size' => $size,'savename' => $savename,'path' => $this->finalFilePath,);}}//返回上传的文件数量return count($this->saveFileInfo);}/*** 取出已上传文件信息,以便进行其它操作** @return array*/public function getSaveFileInfo(){return $this->saveFileInfo;}/*** 检查上传文件大小是否合法** @param int $size* @return boolean*/private function checkSize($size){return $size > $this->maxFileSize) ? false : true;;}/*** 检查文件类型是否合法** @param string $etype* @return boolean*/private function checkType($etype){foreach($this->allowType as $type){if(strcasecmp($etype,$type) == 0) return true;}return false;}/*** 打印信息** @param string $msg*/private function printMsg($msg){return $msg;}/*** 获取文件的扩展名** @param string $filename* @return string*/private function getFileExt($filename){$ext = pathinfo($filename);return $ext['extension'];}/*** 获取文件名** @param string $filename* @param string $type* @return string*/private function getBaseName($filename,$type) {$basename = basename($filename,$type);return $basename;}}?>。
PHP实现多文件上传的方法

PHP实现多⽂件上传的⽅法本⽂实例讲述了PHP实现多⽂件上传的⽅法。
分享给⼤家供⼤家参考。
具体实现⽅法如下:<?phpdefine('ROOT','D:/Program Files/www/test/');class Files_Tool{protected static $allowExt=array('.jpg','.jpeg','.png','.gif','.bmp','.svg','.chm','.pdf','.zip','.rar','.tar','.gz','.bzip2','.ppt','.doc'); public static $wrong=array();public static $path=array();protected static $error=array(0=>'⽂件上传失败,没有错误发⽣,⽂件上传成功',1=>'⽂件上传失败,上传的⽂件超过了 php.ini中upload_max_filesize 选项限制的值',2=>'⽂件上传失败,上传⽂件的⼤⼩超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值',3=>'⽂件上传失败,⽂件只有部分被上传',4=>'⽂件上传失败,没有⽂件被上传',5=>'⽂件上传失败,未允许的后缀',6=>'⽂件上传失败,找不到临时⽂件夹.PHP 4.3.10 和 PHP 5.0.3 引进',7=>'⽂件上传失败,⽂件写⼊失败.PHP 5.1.0 引进',8=>'⽂件上传失败,未接收到表单域的NAME',9=>'⽂件上传失败,,错误未知');public static function upload($name){//检测是否接收到表单域的NAMEif(!isset($_FILES[$name])){self::$wrong[]=8;return false;}//3维数组简化成2维数组$files=array_shift($_FILES);//获取后缀$files=self::get_Ext($files);//处理⽂件次数$n=count($files['name']);for($i=0;$i<$n;$i++){//查看当前⽂件是否有错误信息,有则跳过当前⽂件,处理下个⽂件if($files['error'][$i]!=0){self::$wrong[$i+1]=$files['error'][$i];continue;}//查看当前⽂件的后缀,是否允许,如果不允许,跳过当前⽂件if(!in_array($files['name'][$i],self::$allowExt)){self::$wrong[$i+1]=5;continue;}//路径$dir=self::time_Dir();//⽂件名$name=self::rand_Name();//后缀$ext=$files['name'][$i];//⽂件位置$path=$dir.$name.$ext;//移动临时⽂件,如果失败,跳过当前⽂件if(!move_uploaded_file($files['tmp_name'][$i],$path)){self::$wrong[$i]=9;continue;}//存⼊路径self::$path[$i+1]=strtr($path,array(ROOT=>''));}return self::$path;}//获取后缀的⽅法protected static function get_Ext($arr){if(!is_array($arr) || !isset($arr['name'])){return false;}foreach($arr['name'] as $k=>$v){$arr['name'][$k]=strtolower(strrchr($v,'.'));}return $arr;}//以⽇期⽣成路径protected static function time_Dir(){$dir=ROOT.'Data/images/'.date('Y/m/d/',time());if(!is_dir($dir)){mkdir($dir,0777,true);}return $dir;}//⽣成随机⽂件名protected static function rand_Name(){$str=str_shuffle('1234567890qwertyuiopasdfghjklzxcvbnm'); $str=substr($str,0,6);return $str;}//错误接⼝public static function errors(){foreach(self::$wrong as $k=>$v){self::$wrong[$k]='第'.$k.'个'.self::$error[$k];}return self::$wrong;}}希望本⽂所述对⼤家的php程序设计有所帮助。
php多文件上传解析和代码示例

php多文件上传解析和代码示例自己写的一段多文件上传代码,已测试可用。
要使用PHP实现文件上传功能,我们先来编写两个php文件:test.html和upfiles.php。
其中,test.html页面用于提交文件上传的表单请求,upfiles.php 页面用于接收上传的文件并进行相应处理。
示例一中加入了判断上传的文件是否是文本文件的语句。
【加限制是为了增加安全性】如果要上传任意类型文件,去掉红色代码部分。
upfiles.php代码:示例一:<?php//多文件上传header('Content-Type:text/html;charset=utf-8');$file_Arr = $_FILES['userfile'];//上传文件的相关信息存放在超全局变量$_FILES中。
因此,我们只需要通过$_FILES数组获取上传的文件信息,然后对其进行相应的处理操作即可。
$upfile = 'D:/upload/'; //上传文件的存放路径foreach($file_Arr['error'] as $key => $error){if($error == UPLOAD_ERR_OK ){if($file_Arr['type'][$key] != 'text/plain'){echo "上传的文件不是文本文件";exit;}else{$tmp_name=$file_Arr['tmp_name'][$key]; //提交表单以后,文件上传到服务器,暂时存放在服务器的临时目录里边。
即:文件在服务器上的临时目录。
//注意:文件存放在临时目录时,文件名是不是它本身真实的文件名,而是系统自动给文件分配的一个文件名。
$name=$file_Arr['name'][$key]; //上传文件的文件名$name=iconv("utf-8","GBK",$name);//解决上传中文文件时乱码问题move_uploaded_file($tmp_name,$upfile.$name);//移动服务器临时目录中的文件到存放上传文件的目录,并重命名为真实名称。
php文件上传类程序代码
php文件上传类程序代码文件上传是Web开发中常见的功能之一,它允许用户将文件从本地计算机上传到服务器上。
在PHP中,我们可以通过编写一个文件上传类来实现这个功能。
本文将详细介绍如何编写一个PHP文件上传类程序代码。
一、创建文件上传类首先,我们需要创建一个PHP类来处理文件上传。
以下是一个基本的文件上传类的代码示例:```phpclass FileUploader {private $allowedExtensions = array();private $maxFileSize;private $uploadPath;public function __construct($allowedExtensions, $maxFileSize, $uploadPath) { $this->allowedExtensions = $allowedExtensions;$this->maxFileSize = $maxFileSize;$this->uploadPath = $uploadPath;}public function upload($file) {$fileName = $file['name'];$fileSize = $file['size'];$fileTmp = $file['tmp_name'];$fileError = $file['error'];$fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));$fileDestination = $this->uploadPath . '/' . $fileName;if (!in_array($fileExt, $this->allowedExtensions)) {return 'Invalid file extension.';}if ($fileSize > $this->maxFileSize) {return 'File size exceeds the limit.';}if ($fileError !== 0) {return 'An error occurred while uploading the file.';}if (move_uploaded_file($fileTmp, $fileDestination)) {return 'File uploaded successfully.';} else {return 'Failed to upload file.';}}}```二、使用文件上传类一旦我们创建了文件上传类,就可以在其他PHP文件中使用它来处理文件上传。
php多文件上传类
在网上看到一个比较好的多文件上传类, 自己改良了下, 顺便用 js 实现了多文件浏览,php 文件上传原理都是相同的,多文件上传也只是进行了循环上传而已,当然你也可以使用 swfupload 进行多文件上传! <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" charset=UTF-8">content="text/html; <title>Insert title here</title> <script language="javascript" type="text/javascript"> function AddInput(){ var input=document.createElement('input');//创建一个 input 节点 var br=document.createElement('br');//创建一个 br 节点 input.setAttribute('type','file');//设置 input 节点 type 属性为 file input.setAttribute('name','files[]');//设置 input 节点 name 属性 为 files[],以 数组的方式传递给服务器端 document.myForm.appendChild(br);//把节点添加到 form1表单中 document.myForm.appendChild(input); } </script> </head> <body> <?php /* * 尊重作者:mckee 来自 * 可同时处理用户多个上传文件。
php文件上传类程序代码
php文件上传类程序代码文件上传是Web开辟中常见的功能之一,通过上传文件,用户可以将本地文件上传到服务器上进行处理或者存储。
在PHP中,我们可以使用文件上传类来简化文件上传的过程。
下面是一个基本的PHP文件上传类程序代码示例:```php<?phpclass FileUploader {private $allowedExtensions = array();private $maxFileSize = 0;private $uploadDirectory = '';public function __construct($allowedExtensions, $maxFileSize, $uploadDirectory) {$this->allowedExtensions = $allowedExtensions;$this->maxFileSize = $maxFileSize;$this->uploadDirectory = $uploadDirectory;}public function uploadFile($file) {if ($this->validateFile($file)) {$targetFile = $this->uploadDirectory . basename($file['name']);if (move_uploaded_file($file['tmp_name'], $targetFile)) {return true;} else {return false;}} else {return false;}}private function validateFile($file) {$fileExtension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION)); if (!in_array($fileExtension, $this->allowedExtensions)) {return false;}if ($file['size'] > $this->maxFileSize) {return false;}return true;}}>```以上是一个简单的PHP文件上传类程序代码示例。
PHP文件上传设置和处理(多文件)
PHP⽂件上传设置和处理(多⽂件)<!--upload.php⽂件内容--><?phpheader("Content-Type:text/html;charset=utf-8");/*//原来$_FILES的内容Array([pic] => Array([name] => Array([0] => 175_2426_3ecb275c994a192.jpg[1] => 195_4074_831a070561e20a0.jpg[2] => 46348.jpg[3] => 4e4b68e5a9334.jpg)[type] => Array([0] => image/jpeg[1] => image/jpeg[2] => image/jpeg[3] => image/jpeg)[tmp_name] => Array([0] => C:\wamp\tmp\php30.tmp[1] => C:\wamp\tmp\php31.tmp[2] => C:\wamp\tmp\php32.tmp[3] => C:\wamp\tmp\php33.tmp)[error] => Array([0] => 0[1] => 0[2] => 0[3] => 0)[size] => Array([0] => 8374[1] => 43274[2] => 4052[3] => 108521)))//要转换成如下的格式[pic] = array([0] => Array([name] => 195_4074_831a070561e20a0.jpg[type] => image/jpeg[tmp_name] => C:\wamp\tmp\php45.tmp[error] => 0[size] => 43274)[1] => Array([name] => 195_4074_831a070561e20a0.jpg[type] => image/jpeg[tmp_name] => C:\wamp\tmp\php45.tmp[error] => 0[size] => 43274)[2] => Array([name] => 195_4074_831a070561e20a0.jpg[type] => image/jpeg[tmp_name] => C:\wamp\tmp\php45.tmp[error] => 0[size] => 43274)[3] => Array([name] => 195_4074_831a070561e20a0.jpg[type] => image/jpeg[tmp_name] => C:\wamp\tmp\php45.tmp[error] => 0[size] => 43274))*/$num = count($_FILES['pic']['name']);//长度4for($i=0; $i<$num; $i++) {//第⼀步:判断错误if($_FILES['pic']['error'][$i] > 0) {switch($_FILES['pic']['error'][$i]) {case 1:echo "表⽰上传⽂件的⼤⼩超出了约定值。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
up.html
<form action="upp.php" method="post" enctype="multipart/form-data">
<p>Pictures:<br />
<input type="file" name="pictures[]" /><br />
<input type="file" name="pictures[]" /><br />
<input type="file" name="pictures[]" /><br />
<input type="submit" name="upload" value="添加" />
</p>
</form>
upp.php
<?php
$uploadfile;
if($_POST['upload']=='添加'){
$dest_folder = "picture/"; //上传图片保存的路径图片放在跟你upload.php同级的picture文件夹里
$arr=array(); //定义一个数组存放上传图片的名称方便你以后会用的,如果不用那就不写$count=0;
if(!file_exists($dest_folder)){
mkdir($dest_folder);
}
foreach ($_FILES["pictures"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["pictures"]["tmp_name"][$key];
$name = $_FILES["pictures"]["name"][$key];
$uploadfile = $dest_folder.$name;
move_uploaded_file($tmp_name, $uploadfile);
$arr[$count]=$uploadfile;
// $files=substr($uploadfile,3); //如果你到底的图片名称不是你所要的你可以用截取字符得到
echo $uploadfile."<br />";
echo $files."<br />";
echo $arr[$count]."<br />";
$count++;
}
}
}
?>。