<?php
$fileType = ['jpg', 'jpeg', 'png', 'gif'];
$fileSize = 3145728;
$filePath = '/uploads/';
$fileName = $_FILES['my_file']['name'];
$tempFile = $_FILES['my_file']['tmp_name'];
$uploadError = $_FILES['my_file']['error'];
if ($uploadError > 0) {
switch ($uploadError) {
case 1:
case 2: die('上传文档不允许超过3M');
case 3: die('上传文件不完整');
case 4: die('没有文件被上传');
default: die('未知错误');
}
}
$extension = explode('.', $fileName)[1];
if (!in_array($extension, $fileType)) {
die('不允许上传' . $extension . ' 文件类型');
}
$fileName = date('YmdHis',time()).md5(mt_rand(1,99)). '.' . $extension;
if (is_uploaded_file($tempFile)) {
if (move_uploaded_file($tempFile, __DIR__. $filePath.$fileName)){
echo '<script>alert("上传成功");history.back();</script>';
} else {
die('文件无法移动到指定目录, 请检查目录权限');
}
} else {
die('非法操作');
}
exit();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文件上传</title>
</head>
<body>
<!--请求类型必须是: post-->
<!--数据编码类型: 使用复合类型,通知服务器上传的是文件类型-->
<form action="demo4.php" method="post" enctype="multipart/form-data">
<input type="file" name="my_file" id="">
<input type="hidden" name="MAX_FILE_SIZE" value="3145728">
<button>上传</button>
</form>
</body>
</html>
|