Web 与超全局变量
GET/POST、表单、文件上传、Session。
35 分钟
Web 与超全局变量
本课在 php-essentials Web 请求基础上,系统讲解 GET/POST 表单、文件上传与 Session。对照 Spring MVC 见 spring-boot-essentials;路径 /roadmaps/php。
学习目标
- 处理 GET 查询与 POST 表单并做基本校验
- 安全上传文件并限制类型与大小
- 用 Session 维持登录状态
GET 与 POST
<?php
declare(strict_types=1);
$slug = trim($_GET['slug'] ?? '');
if ($slug === '') {
http_response_code(422);
echo json_encode(['error' => 'slug required']);
exit;
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$title = trim($_POST['title'] ?? '');
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['slug' => $slug, 'title' => $title]);
exit;
}
输出用户数据前务必 htmlspecialchars;JSON 响应用 json_encode。
文件上传
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['cover'])) {
$file = $_FILES['cover'];
if ($file['error'] !== UPLOAD_ERR_OK) {
http_response_code(400);
exit('upload failed');
}
$allowed = ['image/jpeg', 'image/png'];
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $file['tmp_name']);
if (!in_array($mime, $allowed, true)) {
http_response_code(415);
exit('unsupported type');
}
move_uploaded_file($file['tmp_name'], __DIR__ . '/uploads/' . basename($file['name']));
}
Session
session_start();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$_SESSION['user_id'] = 42;
header('Location: /dashboard.php');
exit;
}
$userId = $_SESSION['user_id'] ?? null;
if ($userId === null) {
http_response_code(401);
exit('login required');
}
练习
- 实现登录表单:POST 用户名写入 Session,GET 检查是否已登录
- 限制上传文件 ≤ 2MB,仅允许 jpg/png
- 对照 php-essentials Web 课 复习 front controller
小结
超全局读请求;Session 管状态;上传须校验 MIME。 下一课讲 Web 安全基础。
加载本节练习…