upload.func.php
<?php
function uploadFile($fileInfo, $uploadPath = 'uploads', $flag = true,
$allowExt = array('jpeg', 'jpg', 'png', 'gif'),
$maxSize = 2097152)
{
//判斷錯誤號
if ($fileInfo['error'] > 0) {
$mes = '';
switch ($fileInfo['error']) {
case 1:
$mes = "上傳文件超過了PHP配置文件中upload_max_file";
break;
case 2:
$mes = "超過了表單MAX_FILE_SIZE";
break;
case 3:
$mes = "文件部分被上傳";
break;
case 4:
$mes = "沒有選擇上傳文件";
break;
case 6:
$mes = "沒有找到臨時目錄";
break;
case 7:
case 8:
$mes = "系統錯誤";
break;
}
exit($mes);
} else {
$ext = pathinfo($fileInfo['name'], PATHINFO_EXTENSION);
//檢測文件上傳的類型
if (!in_array($ext, $allowExt)) {
exit("非法文件類型");
}
//檢測文件大小是否符合規范
if ($fileInfo['size'] > $maxSize) {
exit('上傳文件過大');
}
//檢測圖片是否為真實的圖片類型
if ($flag) {
if (!getimagesize($fileInfo['tmp_name'])) {
exit('不是真實的圖片類型');
}
}
//檢測是否是通過HTTP POST 方式上傳的
if (!is_uploaded_file($fileInfo['tmp_name'])) {
exit('文件不是通過HTTP POST方式上傳上來的');
}
if (!file_exists($uploadPath)) {
mkdir($uploadPath, 0777, true);
chmod($uploadPath, 0777);
}
$uniName = md5(uniqid(microtime(true), true)) . '.' . $ext;
$destination = $uploadPath . '/' . $uniName;
if (!@move_uploaded_file($fileInfo['tmp_name'], $destination)) {
exit("文件移動失敗");
}
return array(
'newName' => $destination,
'size' => $fileInfo['size'],
'type' => $fileInfo['type']
);
//return $destination;
}
}
?>
<html>
<head><title></title></head>
<body>
<form action="doAction.php" method="post" enctype="multipart/form-data">
請選擇您要上傳的文件:
<input type="file" name="myFile"><br/>
<input type="submit" value="上傳文件">
</form>
</body>
</html>
doAction.php
<?php
require 'upload.func.php';
$fileInfo = $_FILES['myFile'];
$allowExt = array('jpeg', 'jpg', 'png', 'gif', 'html', 'txt');
$newName = uploadFile($fileInfo, 'imooc', false, $allowExt);
var_dump($newName);
?>
Paste_Image.png
Paste_Image.png