单文件上传php代码
<!DOCTYPE html>
<html lang="en">
<?php
//$_FILES:php超全局变量,保存着上传文件的全部信息
printf('<pre>%s</pre>',print_r($_FILES,true));
/**
* 1.$_FILES:二维数组,每个元素对应一个上传的文件
* 2.name:原始文件名
* 3.type:文件类型,mime类型
* 4.tmp_name:临时目录
* 5.error:错误代码
* 6.size:文件大小(字节表示 byte)
*/
if(isset($_FILES['my_pic'])) {
$name = $_FILES['my_pic']['name'];
$tmpName = $_FILES['my_pic']['tmp_name'];
$error = $_FILES['my_pic']['error'];
if ($error > 0) {
$tips = '<span style="color:red">上传失败</span>';
switch ($error) {
case 1:
$tips .= '上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值。';
break;
case 2:
$tips .= '上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值。';
break;
case 3:
$tips .= '文件只有部分被上传。';
break;
case 4:
$tips .= '没有文件被上传。';
break;
case 6:
$tips .= '找不到临时文件夹。';
break;
case 7:
$tips .= '文件写入失败。';
break;
}
echo "<p>$tips</p>";
} else {
if (is_uploaded_file($tmpName)) {
$allow = ['jpg','jpeg','png','gif'];
$ext = pathinfo($name)['extension'];
if (in_array($ext, $allow)) {
$path = 'uploads/';
$dest = $path . md5($name) . '.' . $ext;
if (move_uploaded_file($tmpName, $dest)) {
echo '上传成功';
echo "<img src='$dest', width='200'>";
} else {
echo '移动失败';
}
} else {
echo '文件类型错误';
}
} else {
echo '非法方式上传';
}
}
}
?>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="" method="POST" enctype="multipart/form-data">
<fieldset>
<legend>单文件上传</legend>
<input type="hidden" name="MAX_FILE_SIZE" value="400000">
<input type="file" name="my_pic">
<button>上传</button>
</fieldset>
</form>
</body>
</html>