首页 > 代码库 > PHP文件上传

PHP文件上传

前台页代码:

 1 <!DOCTYPE HTML> 2 <html> 3     <head> 4         <meta charset="utf-8"> 5     </head> 6     <body> 7         <form action="uploadFile.php" method="POST" enctype="multipart/form-data"> 8             <input type="file" name="img" /> 9             <input type="submit" value="上传" />10         </form>11     </body>12 </html>

 

后台处理代码:

 1 <?php 2   header("Content-type: text/html; charset=utf-8"); 3   /** 4    * uploadFile 文件上传 5    * @param 传入 $_FILES[‘img‘] 6    * return array  7    */ 8   function uploadFile($file){ 9     $result = array();10     $result[‘status‘] = 0;11     12     $suffix = array(‘jpg‘, ‘png‘, ‘jpeg‘, ‘gif‘, ‘ico‘); //允许的文件格式13     $size = 1024000; //文件大小限制14     $path = ‘img/‘; //上传的文件目录15     16     //判断文件是否是通过 HTTP POST17     if(is_uploaded_file($file[‘tmp_name‘])){18         //获取该文件信息19         $info = pathinfo($file[‘name‘]);20         //验证文件合法性21         if(!in_array($info[‘extension‘], $suffix)){22             $result[‘msg‘] = ‘上传的文件不合法!‘;23             return $result;24         } else if($file[‘size‘] > $size){25             $result[‘msg‘] = ‘上传的文件超过规定大小!‘;26             return $result;27         }28         29         //开始上传操作30         $res = move_uploaded_file($file[‘tmp_name‘], $path.time().‘.‘.$info[‘extension‘]);31         //判断是否上传成功32         if($res){33             $result[‘status‘] = 1;34             $result[‘msg‘] = ‘上传的文件超过规定大小!‘;35             return $result;36         }37         $result[‘msg‘] = ‘上传的失败!‘;38         return $result;39     }40     41     $result[‘msg‘] = ‘非法上传途径!‘;42     return $result;43   }44   45   $result = uploadFile($_FILES[‘img‘]);46   47   echo ‘<pre>‘;48   var_dump($result);49   echo ‘</pre>‘;

 

PHP文件上传