StartMVC开发手册

可以快速上手的开发文档

手册目录

请求Request

功能概述

Request 类用于处理 HTTP 请求,提供了获取 GET/POST 参数、请求头、客户端 IP 等功能,同时支持请求类型判断和参数过滤。

详细用法

获取请求参数
GET 参数获取
// 获取单个 GET 参数
$id = Request::get('id');

// 获取 GET 参数并指定默认值
$page = Request::get('page', ['default' => 1]);

// 获取 GET 参数并转换类型
$id = Request::get('id', ['type' => 'int']);
$price = Request::get('price', ['type' => 'float']);

// 获取 GET 参数并应用过滤函数
$keyword = Request::get('keyword', ['function' => 'trim']);

// 组合使用多个选项
$id = Request::get('id', [
    'default' => 0,
    'type' => 'int',
    'filter' => true
]);
POST 参数获取
// 获取单个 POST 参数
$username = Request::post('username');

// 获取所有 POST 数据
$allPostData = Request::post();

// 获取 POST 参数并转换为数组
$tags = Request::post('tags', ['type' => 'array']);

// 禁用 HTML 特殊字符过滤(允许 HTML 标签)
$content = Request::post('content', ['filter' => false]);

// 应用多个处理函数(先trim后strtolower)
$email = Request::post('email', [
    'function' => ['trim', 'strtolower'],
    'type' => 'string'
]);
原始数据获取
// 获取原始 POST 数据
$rawData = Request::postInput();

// 获取并解析 JSON 数据为关联数组
$jsonData = Request::getJson();

// 获取 JSON 数据为对象
$jsonObject = Request::getJson(false);
实例化使用
$request = new Request();

// 获取所有请求参数(GET+POST合并)
$allInputs = $request->all();

// 获取指定键名的输入,不存在则返回默认值
$name = $request->input('name', '游客');

// 不指定键名获取所有输入
$allData = $request->input();

// 获取请求头
$contentType = $request->header('Content-Type', 'text/html');
请求类型检查
// 检查请求方法
$method = Request::method(); // 返回 'GET', 'POST' 等大写字符串

// 检查是否为特定请求方法
if (Request::isGet()) {
    // GET 请求处理逻辑
}

if (Request::isPost()) {
    // POST 请求处理逻辑
}

// 检查是否为 AJAX 请求
$request = new Request();
if ($request->isAjax()) {
    // 返回 JSON 格式数据
    echo json_encode(['success' => true]);
}

// 检查是否为 HTTPS 请求
if (Request::isHttps()) {
    // 安全连接处理
}
获取请求信息
// 获取所有请求头
$headers = Request::headers();

// 获取单个请求头(不区分大小写)
$userAgent = Request::header('User-Agent');
$acceptLanguage = Request::header('accept-language');

// 获取客户端 IP 地址(支持代理)
$clientIp = Request::ip();
高级用法:组合参数处理
// 获取查询参数并应用多个处理函数
// 使用函数名:参数格式,参数中的空白将被替换为当前值
$title = Request::get('title', [
    'function' => [
        'trim',
        'strip_tags',
        'substr:,0,100' // 限制长度为100字符
    ]
]);

// 使用类型转换和自定义处理函数
$amount = Request::post('amount', [
    'type' => 'float',
    'default' => 0.00,
    'function' => 'number_format:,2'
]);

注意事项

  1. filter 选项默认为 true,会对字符串应用 htmlspecialchars 函数
  2. 类型转换发生在过滤函数应用之前
  3. get()post() 方法都通过 Http::handling 处理参数,支持相同的选项