CodeRoadMap
首页路线题库资源库文章社区
CodeRoadMap

程序员的学习成长路线图。内容免费开放,登录后可同步路线图与课时进度。

由 程序员柏风 独立维护 · 关于作者

学习

  • 路线图
  • 课程
  • 面试题
  • 文章
  • 我

更多

  • 资源
  • 社区
  • 关于作者
  • 内容说明

© 2026 CodeRoadMap

津ICP备2026012044号-1·津公网安备12011002026155号·coderoadmap@126.com
PHP 进阶/课时/Web 与超全局变量
RawBlame
课时目录12 节

PHP 进阶

  1. 01PHP 进阶地图
  2. 02语法与数据结构
  3. 03Web 与超全局变量
  4. 04安全基础
  5. 05OOP 深入
  6. 06现代 PHP 工程
  7. 07数据库与 ORM
  8. 08性能与运维
  9. 09测试与静态分析
  10. 10框架生态
  11. 11集成与 CLI
  12. 12综合练习

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 安全基础。

加载本节练习…
← 上一课语法与数据结构下一课 →安全基础