实现多文件上传php类

多文件上传是PHP中的一个基础应用,反正PHPer都会遇到的问题,现在就介绍一个功能完善、强大的多文件上传类给大家吧,能用上这个类的地方会很多,代码如下:

  1. <?php
  2. class Upload{
  3. var $saveName;// 保存名
  4. var $savePath;// 保存路径
  5. var $fileFormat = array('gif','jpg','doc','application/octet-stream');// 文件格式&MIME限定
  6. var $overwrite = 0;// 覆盖模式
  7. var $maxSize = 0;// 文件最大字节
  8. var $ext;// 文件扩展名
  9. var $thumb = 0;// 是否生成缩略图
  10. var $thumbWidth = 130;// 缩略图宽
  11. var $thumbHeight = 130;// 缩略图高
  12. var $thumbPrefix = "_thumb_";// 缩略图前缀
  13. var $errno;// 错误代号
  14. var $returnArray= array();// 所有文件的返回信息
  15. var $returninfo= array();// 每个文件返回信息
  16. // 构造函数
  17. // @param $savePath 文件保存路径
  18. // @param $fileFormat 文件格式限制数组
  19. // @param $maxSize 文件最大尺寸
  20. // @param $overwriet 是否覆盖 1 允许覆盖 0 禁止覆盖
  21. function Upload($savePath, $fileFormat='',$maxSize = 0, $overwrite = 0) {
  22. $this->setSavepath($savePath);
  23. $this->setFileformat($fileFormat);
  24. $this->setMaxsize($maxSize);
  25. $this->setOverwrite($overwrite);
  26. $this->setThumb($this->thumb, $this->thumbWidth,$this->thumbHeight);
  27. $this->errno = 0;
  28. }
  29. // 上传
  30. // @param $fileInput 网页Form(表单)中input的名称
  31. // @param $changeName 是否更改文件名
  32. function run($fileInput,$changeName = 1){
  33. if(isset($_FILES[$fileInput])){
  34. $fileArr = $_FILES[$fileInput];
  35. if(is_array($fileArr['name'])){//上传同文件域名称多个文件
  36. for($i = 0; $i < count($fileArr['name']); $i++){
  37. $ar['tmp_name'] = $fileArr['tmp_name'][$i];
  38. $ar['name'] = $fileArr['name'][$i];
  39. $ar['type'] = $fileArr['type'][$i];
  40. $ar['size'] = $fileArr['size'][$i];
  41. $ar['error'] = $fileArr['error'][$i];
  42. $this->getExt($ar['name']);//取得扩展名,赋给$this->ext,下次循环会更新
  43. $this->setSavename($changeName == 1 ? '' : $ar['name']);//设置保存文件名
  44. if($this->copyfile($ar)){
  45. $this->returnArray[] = $this->returninfo;
  46. }else{
  47. $this->returninfo['error'] = $this->errmsg();
  48. $this->returnArray[] = $this->returninfo;
  49. }
  50. }
  51. return $this->errno ? false : true;
  52. }else{//上传单个文件
  53. $this->getExt($fileArr['name']);//取得扩展名
  54. $this->setSavename($changeName == 1 ? '' : $fileArr['name']);//设置保存文件名
  55. if($this->copyfile($fileArr)){
  56. $this->returnArray[] = $this->returninfo;
  57. }else{
  58. $this->returninfo['error'] = $this->errmsg();
  59. $this->returnArray[] = $this->returninfo;
  60. }
  61. return $this->errno ? false : true;
  62. }
  63. return false;
  64. }else{
  65. $this->errno = 10;
  66. return false;
  67. }
  68. }
  69. // 单个文件上传
  70. // @param $fileArray 文件信息数组
  71. function copyfile($fileArray){
  72. $this->returninfo = array();
  73. // 返回信息
  74. $this->returninfo['name'] = $fileArray['name'];
  75. $this->returninfo['md5'] = @md5_file($fileArray['tmp_name']);
  76. $this->returninfo['saveName'] = $this->saveName;
  77. $this->returninfo['size'] = number_format( ($fileArray['size'])/1024 , 0, '.', ' ');//以KB为单位
  78. $this->returninfo['type'] = $fileArray['type'];
  79. // 检查文件格式
  80. if (!$this->validateFormat()){
  81. $this->errno = 11;
  82. return false;
  83. }
  84. // 检查目录是否可写
  85. if(!@is_writable($this->savePath)){
  86. $this->errno = 12;
  87. return false;
  88. }
  89. // 如果不允许覆盖,检查文件是否已经存在
  90. //if($this->overwrite == 0 && @file_exists($this->savePath.$fileArray['name'])){
  91. // $this->errno = 13;
  92. // return false;
  93. //}
  94. // 如果有大小限制,检查文件是否超过限制
  95. if ($this->maxSize != 0 ){
  96. if ($fileArray["size"] > $this->maxSize){
  97. $this->errno = 14;
  98. return false;
  99. }
  100. }
  101. // 文件上传
  102. if(!@move_uploaded_file($fileArray["tmp_name"], $this->savePath.$this->saveName)){
  103. $this->errno = $fileArray["error"];
  104. return false;
  105. }elseif( $this->thumb ){// 创建缩略图
  106. $CreateFunction = "imagecreatefrom".($this->ext == 'jpg' ? 'jpeg' : $this->ext);
  107. $SaveFunction = "image".($this->ext == 'jpg' ? 'jpeg' : $this->ext);
  108. if (strtolower($CreateFunction) == "imagecreatefromgif"
  109. && !function_exists("imagecreatefromgif")) {
  110. $this->errno = 16;
  111. return false;
  112. } elseif (strtolower($CreateFunction) == "imagecreatefromjpeg"
  113. && !function_exists("imagecreatefromjpeg")) {
  114. $this->errno = 17;
  115. return false;
  116. } elseif (!function_exists($CreateFunction)) {
  117. $this->errno = 18;
  118. return false;
  119. }
  120. $Original = @$CreateFunction($this->savePath.$this->saveName);
  121. if (!$Original) {$this->errno = 19; return false;}
  122. $originalHeight = ImageSY($Original);
  123. $originalWidth = ImageSX($Original);
  124. $this->returninfo['originalHeight'] = $originalHeight;
  125. $this->returninfo['originalWidth'] = $originalWidth;
  126. /*
  127. if (($originalHeight < $this->thumbHeight
  128. && $originalWidth < $this->thumbWidth)) {
  129. // 如果比期望的缩略图小,那只Copy
  130. move_uploaded_file($this->savePath.$this->saveName,
  131. $this->savePath.$this->thumbPrefix.$this->saveName);
  132. } else {
  133. if( $originalWidth > $this->thumbWidth ){// 宽 > 设定宽度
  134. $thumbWidth = $this->thumbWidth ;
  135. $thumbHeight = $this->thumbWidth * ( $originalHeight / $originalWidth );
  136. if($thumbHeight > $this->thumbHeight){// 高 > 设定高度
  137. $thumbWidth = $this->thumbHeight * ( $thumbWidth / $thumbHeight );
  138. $thumbHeight = $this->thumbHeight ;
  139. }
  140. }elseif( $originalHeight > $this->thumbHeight ){// 高 > 设定高度
  141. $thumbHeight = $this->thumbHeight ;
  142. $thumbWidth = $this->thumbHeight * ( $originalWidth / $originalHeight );
  143. if($thumbWidth > $this->thumbWidth){// 宽 > 设定宽度
  144. $thumbHeight = $this->thumbWidth * ( $thumbHeight / $thumbWidth );
  145. $thumbWidth = $this->thumbWidth ;
  146. }
  147. }
  148. */
  149. $radio=max(($originalWidth/$this->thumbWidth),($originalHeight/$this->thumbHeight));
  150. $thumbWidth=(int)$originalWidth/$radio;
  151. $thumbHeight=(int)$originalHeight/$radio;
  152. if ($thumbWidth == 0) $thumbWidth = 1;
  153. if ($thumbHeight == 0) $thumbHeight = 1;
  154. $createdThumb = imagecreatetruecolor($thumbWidth, $thumbHeight);
  155. if ( !$createdThumb ) {$this->errno = 20; return false;}
  156. if ( !imagecopyresampled($createdThumb, $Original, 0, 0, 0, 0,
  157. $thumbWidth, $thumbHeight, $originalWidth, $originalHeight) )
  158. {$this->errno = 21; return false;}
  159. if ( !$SaveFunction($createdThumb,
  160. $this->savePath.$this->thumbPrefix.$this->saveName) )
  161. {$this->errno = 22; return false;}
  162. }
  163. // 删除临时文件
  164. /*
  165. if(!@$this->del($fileArray["tmp_name"])){
  166. return false;
  167. }
  168. */
  169. return true;
  170. }
  171. // 文件格式检查,MIME检测
  172. function validateFormat(){
  173. if(!is_array($this->fileFormat)
  174. || in_array(strtolower($this->ext), $this->fileFormat)
  175. || in_array(strtolower($this->returninfo['type']), $this->fileFormat) )
  176. return true;
  177. else
  178. return false;
  179. }
  180. // 获取文件扩展名
  181. // @param $fileName 上传文件的原文件名
  182. function getExt($fileName){
  183. $ext = explode(".", $fileName);
  184. $ext = $ext[count($ext) - 1];
  185. $this->ext = strtolower($ext);
  186. }
  187. // 设置上传文件的最大字节限制
  188. // @param $maxSize 文件大小(bytes) 0:表示无限制
  189. function setMaxsize($maxSize){
  190. $this->maxSize = $maxSize;
  191. }
  192. // 设置文件格式限定
  193. // @param $fileFormat 文件格式数组
  194. function setFileformat($fileFormat){
  195. if(is_array($fileFormat)){$this->fileFormat = $fileFormat ;}
  196. }
  197. // 设置覆盖模式
  198. // @param overwrite 覆盖模式 1:允许覆盖 0:禁止覆盖
  199. function setOverwrite($overwrite){
  200. $this->overwrite = $overwrite;
  201. }
  202. // 设置保存路径
  203. // @param $savePath 文件保存路径:以 "/" 结尾,若没有 "/",则补上
  204. function setSavepath($savePath){
  205. $this->savePath = substr( str_replace("\","/", $savePath) , -1) == "/"
  206. ? $savePath : $savePath."/";
  207. }
  208. // 设置缩略图
  209. // @param $thumb = 1 产生缩略图 $thumbWidth,$thumbHeight 是缩略图的宽和高
  210. function setThumb($thumb, $thumbWidth = 0,$thumbHeight = 0){
  211. $this->thumb = $thumb;
  212. if($thumbWidth) $this->thumbWidth = $thumbWidth;
  213. if($thumbHeight) $this->thumbHeight = $thumbHeight;
  214. }
  215. // 设置文件保存名
  216. // @param $saveName 保存名,如果为空,则系统自动生成一个随机的文件名
  217. function setSavename($saveName){
  218. if ($saveName == ''){ // 如果未设置文件名,则生成一个随机文件名
  219. $name = date('YmdHis')."_".rand(100,999).'.'.$this->ext;
  220. //判断文件是否存在,不允许重复文件
  221. if(file_exists($this->savePath . $name)){
  222. $name = setSavename($saveName);
  223. }
  224. } else {
  225. $name = $saveName;
  226. }
  227. $this->saveName = $name;
  228. }
  229. // 删除文件
  230. // @param $fileName 所要删除的文件名
  231. function del($fileName){
  232. if(!@unlink($fileName)){
  233. $this->errno = 15;
  234. return false;
  235. }
  236. return true;
  237. }
  238. // 返回上传文件的信息
  239. function getInfo(){
  240. return $this->returnArray;
  241. }
  242. // 得到错误信息
  243. function errmsg(){
  244. $uploadClassError = array(
  245. 0 =>'There is no error, the file uploaded with success. ',
  246. 1 =>'The uploaded file exceeds the upload_max_filesize directive in php.ini.',
  247. 2 =>'The uploaded file exceeds the MAX_FILE_SIZE that was specified in the HTML form.',
  248. 3 =>'The uploaded file was only partially uploaded. ',
  249. 4 =>'No file was uploaded. ',
  250. 6 =>'Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3. ',
  251. 7 =>'Failed to write file to disk. Introduced in PHP 5.1.0. ',
  252. 10 =>'Input name is not unavailable!',
  253. 11 =>'The uploaded file is Unallowable!',
  254. 12 =>'Directory unwritable!',
  255. 13 =>'File exist already!',
  256. 14 =>'File is too big!',
  257. 15 =>'Delete file unsuccessfully!',
  258. 16 =>'Your version of PHP does not appear to have GIF thumbnailing support.',
  259. 17 =>'Your version of PHP does not appear to have JPEG thumbnailing support.',
  260. 18 =>'Your version of PHP does not appear to have pictures thumbnailing support.',
  261. 19 =>'An error occurred while attempting to copy the source image .
  262. Your version of php ('.phpversion().') may not have this image type support.',
  263. 20 =>'An error occurred while attempting to create a new image.',
  264. 21 =>'An error occurred while copying the source image to the thumbnail image.',
  265. 22 =>'An error occurred while saving the thumbnail image to the filesystem.
  266. Are you sure that PHP has been configured with both read and write access on this folder?',
  267. );
  268. if ($this->errno == 0)
  269. return false;
  270. else
  271. return $uploadClassError[$this->errno];
  272. }
  273. }
  274. ?>
  275. 如何使用这个类呢?
  276. <?php
  277. //如果收到表单传来的参数,则进行上传处理,否则显示表单
  278. if(isset($_FILES['uploadinput'])){
  279. //建目录函数,其中参数$directoryName最后没有"/",
  280. //要是有的话,以'/'打散为数组的时候,最后将会出现一个空值
  281. function makeDirectory($directoryName) {
  282. $directoryName = str_replace("\","/",$directoryName);
  283. $dirNames = explode('/', $directoryName);
  284. $total = count($dirNames) ;
  285. $temp = '';
  286. for($i=0; $i<$total; $i++) {
  287. $temp .= $dirNames[$i].'/';
  288. if (!is_dir($temp)) {
  289. $oldmask = umask(0);
  290. if (!mkdir($temp, 0777)) exit("不能建立目录 $temp");
  291. umask($oldmask);
  292. }
  293. }
  294. return true;
  295. }
  296. if($_FILES['uploadinput']['name'] <> ""){
  297. //包含上传文件类
  298. require_once ('upload_class.php');
  299. //设置文件上传目录
  300. $savePath = "upload";
  301. //创建目录
  302. makeDirectory($savePath);
  303. //允许的文件类型
  304. $fileFormat = array('gif','jpg','jpge','png');
  305. //文件大小限制,单位: Byte,1KB = 1000 Byte
  306. //0 表示无限制,但受php.ini中upload_max_filesize设置影响
  307. $maxSize = 0;
  308. //覆盖原有文件吗? 0 不允许 1 允许
  309. $overwrite = 0;
  310. //初始化上传类
  311. $f = new Upload( $savePath, $fileFormat, $maxSize, $overwrite);
  312. //如果想生成缩略图,则调用成员函数 $f->setThumb();
  313. //参数列表: setThumb($thumb, $thumbWidth = 0,$thumbHeight = 0)
  314. //$thumb=1 表示要生成缩略图,不调用时,其值为 0
  315. //$thumbWidth 缩略图宽,单位是像素(px),留空则使用默认值 130
  316. //$thumbHeight 缩略图高,单位是像素(px),留空则使用默认值 130
  317. $f->setThumb(1);
  318. //参数中的uploadinput是表单中上传文件输入框input的名字
  319. //后面的0表示不更改文件名,若为1,则由系统生成随机文件名
  320. if (!$f->run('uploadinput',1)){
  321. //通过$f->errmsg()只能得到最后一个出错的信息,
  322. //详细的信息在$f->getInfo()中可以得到。
  323. echo $f->errmsg()."<br>n";
  324. }
  325. //上传结果保存在数组returnArray中。
  326. echo "<pre>";
  327. print_r($f->getInfo());
  328. echo "</pre>";
  329. }
  330. }else{
  331. ?>
  332. <form enctype="multipart/form-data" action="" method="POST">
  333. Send this file: <br />
  334. <input name="uploadinput[]" type="file"><br />
  335. <input name="uploadinput[]" type="file"><br />
  336. <input name="uploadinput[]" type="file"><br />
  337. <input type="submit" value="Send File"><br />
  338. </form>
  339. <?php
  340. }
  341. ?>