实例(1. 文件上传的原理与实现)
<?php if($_SERVER['REQUEST_METHOD']) { // 判断请求类型 //设置允许的文件类型 $allowed = ['image/jpeg','image/jpg','image/png']; // echo '<pre>' . print_r($_FILES,true); $type = $_FILES['user_pic']['type']; //获取用户上传文件的类型 $tmpName = $_FILES['user_pic']['tmp_name']; //获取用户上传文件的临时文件名 $name = $_FILES['user_pic']['name']; //获取用户上传文件的文件名 $error = $_FILES['user_pic']['error']; //获取用户上传是否成功的状态信息 if ($error > 0) { echo '<script>alert("上传失败")</script>'; } elseif (in_array($type,$allowed)) { //将文件从临时目录移动到目标目录中 if (move_uploaded_file($tmpName,'./uploads/'.$name)) { echo '<script>alert("上传成功")</script>'; } } } ?> <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <h2>上传用户头像</h2> <!--1.请求类型必须是POST--> <!--2.这个要设置成enctype="multipart/form-data"--> <form action="" method="post" enctype="multipart/form-data"> 请选择头像: <input type="file" name="user_pic" id="user_pic"> <button id="btn">上传</button> </form> </body> </html>
运行实例 »
点击 "运行实例" 按钮查看在线实例