使用 php -S 启动内置服务器,通过 $_SERVER['REQUEST_URI'] 解析路径,利用 switch 或路由数组匹配请求,配合 json_encode 返回标准 JSON 响应。

RESTful 路由与请求解析
PHP 内置服务器支持单入口文件处理所有请求。开发者需从 $_SERVER['REQUEST_URI'] 中提取路径,忽略查询参数,并根据 HTTP 方法(GET/POST/PUT/DELETE)分发逻辑。

在开发环境中,无需配置 Nginx 或 Apache 的 RewriteRule。直接运行 php -S localhost:8080 index.php 即可。核心在于统一入口后的路径拆分。例如,将 /api/users/123 拆分为资源 users 和 ID 123。这种硬编码方式适合小型项目或快速原型,避免了引入 Composer 依赖的开销。
完整 API 实现与运行验证
将以下代码保存为 index.php,在终端执行 php -S localhost:8080,然后访问 http://localhost:8080/api/items 查看结果。

<?php
header('Content-Type: application/json');
// 模拟内存数据库
$items = [
['id' => 1, 'name' => 'Item A'],
['id' => 2, 'name' => 'Item B']
];
// 解析路由
$requestUri = $_SERVER['REQUEST_URI'];
$path = parse_url($requestUri, PHP_URL_PATH);
$method = $_SERVER['REQUEST_METHOD'];
// 简单路由匹配
if ($path === '/api/items') {
if ($method === 'GET') {
http_response_code(200);
echo json_encode(['data' => $items]);
} elseif ($method === 'POST') {
$input = json_decode(file_get_contents('php://input'), true);
if (empty($input['name'])) {
http_response_code(400);
echo json_encode(['error' => 'Name is required']);
exit;
}
$newItem = ['id' => count($items) + 1, 'name' => $input['name']];
$items[] = $newItem;
http_response_code(201);
echo json_encode(['data' => $newItem]);
} else {
http_response_code(405);
echo json_encode(['error' => 'Method not allowed']);
}
} else {
http_response_code(404);
echo json_encode(['error' => 'Not found']);
}
运行后,GET 请求返回 200 及所有物品列表;POST 请求若缺少 name 字段返回 400 错误,成功则返回 201 及新对象。这验证了路由解析和状态码设置的正确性。
该程序模拟了一个简单的内存数据库,演示了 GET 获取列表、POST 创建资源的流程。确保输出包含正确的 Content-Type: application/json 头,这是前端解析的关键。
HTTP 状态码与错误处理细节
必须根据操作结果设置对应的 HTTP 状态码,如 200 OK、201 Created 或 404 Not Found,而非仅依赖 JSON 中的业务状态字段。
在上一节的代码中,如果 POST 数据缺失关键字段,应返回 400 状态码并附带错误信息。开发者常忽略这一点,导致前端难以区分网络错误和业务校验失败。通过 http_response_code() 函数可精确控制响应头,确保符合 RESTful 规范。