標籤:php;檔案上傳
<?php/**檔案上傳***///var_dump($_FILES);/* 多檔案上傳處理$data = $_FILES[‘icon‘];$name = $data[‘name‘];if (is_array($name)) {for ($i=0; $i<count($name); $i++) {echo $data[‘tmp_name‘][$i].‘<br />‘;}} else {echo ‘單個檔案上傳‘;}*/$mimes = [‘image/jpeg‘,‘image/png‘,‘image/gif‘];$suffixs = [‘jpg‘,‘jpeg‘,‘pjpeg‘,‘png‘,‘gif‘];//var_dump(upload(‘icon‘,$mimes,$suffixs,‘upload‘,true));function upload($key,$mimes,$suffixs,$path=null,$rand_name=false){$data = $_FILES[$key];if ($error = $data[‘error‘]) {switch ($error) {case UPLOAD_ERR_INI_SIZE:$msg = ‘超過了upload_max_filesize的值‘;break;case UPLOAD_ERR_FORM_SIZE:$msg = ‘超過了表單中MAX_FILE_SIZE的值‘;break;case UPLOAD_ERR_PARTIAL:$msg = ‘部分檔案上傳‘;break;case UPLOAD_ERR_NO_FILE:$msg = ‘沒有檔案上傳‘;break;case UPLOAD_ERR_NO_TMP_DIR:$msg = ‘沒有找到臨時目錄‘;break;case UPLOAD_ERR_CANT_WRITE:$msg = ‘檔案寫入失敗‘;break;}return [‘error‘=>$error,‘msg‘=>$msg];} else if ($data[‘size‘] > pow(1024,2)*2) {$msg = ‘檔案超過自訂的大小2M‘;return [‘error‘=>0,‘msg‘=>$msg];}if (!in_array($data[‘type‘],$mimes)) {$msg = ‘不支援的MIME‘;return [‘error‘=>0,‘msg‘=>$msg];}$suffix = pathinfo($data[‘name‘])[‘extension‘];if (!in_array($suffix, $suffixs)) {$msg = ‘不支援的尾碼名‘;return [‘error‘=>0,‘msg‘=>$msg];}if (!is_uploaded_file($data[‘tmp_name‘])) {$msg = ‘不是上傳檔案‘;return [‘error‘=>0,‘msg‘=>$msg];}if ($path) {$path = rtrim($path,‘/\\‘) . ‘/‘;} else {$path = ‘./‘;}$path .= date(‘Y/m/d‘) . ‘/‘;if (!file_exists($path)) {mkdir($path, 0777, true);}if ($rand_name) {$name = uniqid(). ‘.‘ . $suffix;} else {$name = $data[‘name‘];}$pathname = $path . $name;if (move_uploaded_file($data[‘tmp_name‘],$pathname)) {return [‘error‘=>200,‘msg‘=>$pathname];} else {$msg = ‘上傳失敗‘;return [‘error‘=>0,‘msg‘=>$msg];}}
本文出自 “你好我是森林” 部落格,請務必保留此出處http://chensenlin.blog.51cto.com/10559465/1844578
PHP中封裝上傳檔案函數