PHP 怎么PHP 请求解析

wen PHP项目 1

本文目录导读:

PHP 怎么PHP 请求解析

  1. GET 请求解析
  2. POST 请求解析
  3. JSON 请求解析
  4. 文件上传解析
  5. URL 参数解析
  6. 使用 Request 对象(框架风格)
  7. 实战示例:完整的请求处理
  8. 调试技巧
  9. 注意事项

在PHP中,处理请求解析是一个非常核心的功能,我来为你详细讲解几种主要的请求解析方式:

GET 请求解析

// URL: http://example.com/page.php?name=John&age=25
// 获取单个参数
$name = $_GET['name']; // "John"
$age = $_GET['age'];   // "25"
// 检查参数是否存在
if (isset($_GET['name'])) {
    echo "Name: " . $_GET['name'];
}
// 使用 ?? 运算符简化(PHP 7+)
$name = $_GET['name'] ?? 'default'; // 如果不存在则使用默认值

POST 请求解析

// HTML表单提交
// <form method="POST" action="process.php">
//   <input name="username" type="text">
//   <input name="password" type="password">
// </form>
// 解析POST数据
$username = $_POST['username'] ?? '';
$password = $_POST['password'] ?? '';
// 批量处理
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = [
        'username' => $_POST['username'] ?? '',
        'email' => $_POST['email'] ?? '',
        'age' => intval($_POST['age'] ?? 0)
    ];
}

JSON 请求解析

// 前端发送JSON
// fetch('/api.php', {
//     method: 'POST',
//     headers: {'Content-Type': 'application/json'},
//     body: JSON.stringify({name: "John", age: 30})
// });
// 服务端解析
$json = file_get_contents('php://input');
$data = json_decode($json, true); // true 转为关联数组
// 或使用对象方式
$data = json_decode($json);
$name = $data->name;
$age = $data->age;

文件上传解析

// HTML表单
// <form method="POST" enctype="multipart/form-data">
//   <input type="file" name="document">
// PHP处理
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['document'])) {
    $file = $_FILES['document'];
    $fileName = $file['name'];
    $fileType = $file['type'];
    $fileSize = $file['size'];
    $fileTmp = $file['tmp_name'];
    $fileError = $file['error'];
    // 移动文件到指定目录
    if ($fileError === UPLOAD_ERR_OK) {
        move_uploaded_file($fileTmp, 'uploads/' . $fileName);
    }
}

URL 参数解析

// URL: http://example.com/user/123/profile
// 方法1:使用 parse_url
$url = 'http://example.com/user/123/profile';
$parts = parse_url($url);
echo $parts['path']; // "/user/123/profile"
// 方法2:使用 $_SERVER
$requestUri = $_SERVER['REQUEST_URI'];
$pathParts = explode('/', trim($requestUri, '/'));
// 方法3:使用 parse_str
$queryString = $_SERVER['QUERY_STRING'] ?? '';
parse_str($queryString, $params);

使用 Request 对象(框架风格)

// 创建简单的请求类
class Request {
    public function get($key, $default = null) {
        return $_GET[$key] ?? $default;
    }
    public function post($key, $default = null) {
        return $_POST[$key] ?? $default;
    }
    public function input($key, $default = null) {
        // 先检查 POST,再检查 GET
        return $_POST[$key] ?? $_GET[$key] ?? $default;
    }
    public function all() {
        return array_merge($_GET, $_POST);
    }
    public function method() {
        return $_SERVER['REQUEST_METHOD'];
    }
    public function isGet() {
        return $this->method() === 'GET';
    }
    public function isPost() {
        return $this->method() === 'POST';
    }
}
// 使用
$request = new Request();
$name = $request->input('name', 'default');

实战示例:完整的请求处理

<?php
header('Content-Type: application/json; charset=utf-8');
class RequestHandler {
    private $data = [];
    public function __construct() {
        $this->parseRequest();
    }
    private function parseRequest() {
        $method = $_SERVER['REQUEST_METHOD'];
        switch ($method) {
            case 'GET':
                $this->data = $_GET;
                break;
            case 'POST':
                $contentType = $_SERVER['CONTENT_TYPE'] ?? '';
                if (strpos($contentType, 'application/json') !== false) {
                    // JSON 请求
                    $json = file_get_contents('php://input');
                    $this->data = json_decode($json, true) ?? [];
                } else {
                    // 普通表单提交
                    $this->data = $_POST;
                }
                break;
            case 'PUT':
            case 'DELETE':
                parse_str(file_get_contents('php://input'), $this->data);
                break;
        }
    }
    public function get($key, $default = null) {
        return $this->data[$key] ?? $default;
    }
    public function all() {
        return $this->data;
    }
    public function validate($rules) {
        $errors = [];
        foreach ($rules as $field => $rule) {
            $value = $this->get($field);
            if ($rule['required'] && empty($value)) {
                $errors[$field] = "{$field} is required";
            }
            if (isset($rule['min']) && strlen($value) < $rule['min']) {
                $errors[$field] = "{$field} min length is {$rule['min']}";
            }
        }
        return $errors;
    }
}
// 使用示例
$handler = new RequestHandler();
$errors = $handler->validate([
    'name' => ['required' => true, 'min' => 2],
    'email' => ['required' => true]
]);
if (!empty($errors)) {
    echo json_encode(['success' => false, 'errors' => $errors]);
    exit;
}
$response = [
    'success' => true,
    'data' => $handler->all()
];
echo json_encode($response);

调试技巧

// 查看所有请求数据
print_r($_REQUEST); // POST + GET
// 查看请求头
print_r(getallheaders());
// 查看原始请求体
echo file_get_contents('php://input');
// 查看服务器变量
print_r($_SERVER);

注意事项

  1. 安全性:始终验证和清理输入数据
  2. 编码问题:注意 URL 编码和解码
  3. 大数据:处理大文件上传时注意 php.ini 配置
  4. 字符集:设置正确的字符编码 header('Content-Type: text/html; charset=utf-8');

这些方法涵盖了PHP中绝大多数的请求解析场景,选择哪种方式取决于你的具体需求和项目架构。

抱歉,评论功能暂时关闭!