檔案上傳操作
程式碼如下:
<?php
header("Content-type: text/html; charset=utf8");
/**
* 函式名:upload
* 描述:檔案上傳
* @param array $file 上傳檔案的資訊
* @param array $allow 檔案上傳的型別
* @param string $path 檔案上傳的路徑
* @param int $maxsize = 2*1024*1024 允許上傳的檔案的大小
* @return false|$newname 如果上傳失敗就返回false,成功則返回檔案的新名字
*/
function upload($file,$allow,$path,$maxsize=2097152){
$res = array('code'=>1,'msg' => '上傳成功!','data'=>[]);
// 判斷系統錯誤
switch ($file['error']) {
case 1:
$res['code'] = 0;
$res['msg'] = '上傳錯誤,超出了檔案限制的大小!';
return $res;
case 2:
$res['msg'] = '上傳錯誤,超出了表單允許的大小!';
return $res;
case 3:
$res['code'] = 0;
$res['msg'] = '上傳錯誤,檔案上傳不完整!';
return $res;
case 4:
$res['code'] = 0;
$res['msg'] = '請先選擇要上傳的檔案!';
return $res;
case 6:
case 7:
$res['msg'] = '對不起,伺服器繁忙,請稍後再試!';
return $res;
}
// 判斷檔案大小
if ($file['size'] > $maxsize) {
$res['code'] = 0;
$res['msg'] = '超出檔案大小,允許的最大值為:'. $maxsize . '位元組';
return $res;
}
// 判斷檔案型別 image/png
if (!in_array($file['type'], $allow)) {
// 檔案型別非法
$res['code'] = 0;
$res['msg'] = '上傳的檔案型別不正確,允許的型別有:' . implode(',', $allow);
return $res;
}
// 得到檔案的新名字
$newname = randName($file['name']);
// 移動臨時檔案到指定路徑
$target = $path . '/' . $newname;
if (move_uploaded_file($file['tmp_name'], $target)) {
$res['data'] = $newname;
return $res;
}else {
$res['code'] = 0;
$res['msg'] = '發生未知錯誤,上傳失敗!';
return $res;
}
}
/**
* 函式名:randName
* 描述:定義一個產生隨機名字的函式
* @param string $filename 檔案的舊名字
* @param string $newname 檔案的新名字
*/
function randName($filename) {
// 生成檔名的時間部分
$newname = date('YmdHis');
// 加上隨機的六位數
$str = '0456789';
// 得到六位隨機數
for ($i=0; $i < 6; $i++) {
// 將每次得到的隨機數加到新名字後
$index = mt_rand(0,strlen($str));
$index = $index <= 0 ? 0 : $index -1;
$newname .= $str[$index];
}
// 加上字尾名
$newname .= strrchr($filename, '.');
return $newname;
}
// 獲取上傳檔案
$file = $_FILES["uploadfile"];
// 允許上傳的型別
$allowArr = array('image/png','image/jpeg');
// 上傳到當前目前下
$path = '.';
// 呼叫上傳方法
$uploadRes = upload($file,$allowArr,$path);
var_dump($uploadRes);
執行成功結果如下:
執行失敗結果如下: