使⽤PHP实现⼀个简单的RESTful API,⽀持创建、查询、更新和删除操作
封面图
•
2025-10-21
•
PHP
212
0
0
0
下面是一个使用 **PHP** 实现的简单 **RESTful API**,支持 **创建(Create)**、**查询(Read)**、**更新(Update)** 和 **删除(Delete)** 操作。这个示例使用了一个简单的内存数组来模拟数据库。 --- ## ✅ 功能说明 - 使用 `$_SERVER['REQUEST_METHOD']` 判断请求类型(GET, POST, PUT, DELETE) - 使用 `json_encode()` 返回 JSON 格式数据 - 使用 `file_get_contents('php://input')` 获取原始输入数据(用于 PUT 和 POST) --- ## 📁 文件结构 ``` rest-api/ │ ├── index.php ``` --- ## 💻 `index.php` 示例代码: ```php <?php header("Content-Type: application/json"); // 模拟数据库(使用数组存储数据) $database = [ 1 => ['name' => 'Alice', 'email' => 'alice@example.com'], 2 => ['name' => 'Bob', 'email' => 'bob@example.com'], ]; // 获取请求方法 $requestMethod = $_SERVER['REQUEST_METHOD']; // 获取 URL 中的 ID(如 /api/1) $uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH); $segments = explode('/', $uri); $id = isset($segments[2]) ? (int)$segments[2] : null; switch ($requestMethod) { case 'GET': if ($id) { // 查询单个资源 if (isset($database[$id])) { echo json_encode($database[$id]); } else { http_response_code(404); echo json_encode(['error' => 'Resource not found']); } } else { // 查询所有资源 echo json_encode($database); } break; case 'POST': // 创建新资源 $data = json_decode(file_get_contents('php://input'), true); if (!empty($data)) { $newId = max(array_keys($database)) + 1; $database[$newId] = $data; http_response_code(201); echo json_encode(['id' => $newId, 'message' => 'Resource created']); } else { http_response_code(400); echo json_encode(['error' => 'Invalid input']); } break; case 'PUT': if ($id) { // 更新资源 $data = json_decode(file_get_contents('php://input'), true); if (isset($database[$id])) { $database[$id] = $data; echo json_encode(['id' => $id, 'message' => 'Resource updated']); } else { http_response_code(404); echo json_encode(['error' => 'Resource not found']); } } else { http_response_code(400); echo json_encode(['error' => 'ID required for update']); } break; case 'DELETE': if ($id) { // 删除资源 if (isset($database[$id])) { unset($database[$id]); echo json_encode(['id' => $id, 'message' => 'Resource deleted']); } else { http_response_code(404); echo json_encode(['error' => 'Resource not found']); } } else { http_response_code(400); echo json_encode(['error' => 'ID required for deletion']); } break; default: http_response_code(405); echo json_encode(['error' => 'Method not allowed']); break; } ``` --- ## 🧪 示例请求(使用 curl 或 Postman) ### 1. 获取所有资源 ```bash curl -X GET http://localhost/rest-api/index.php ``` ### 2. 获取单个资源 ```bash curl -X GET http://localhost/rest-api/index.php/1 ``` ### 3. 创建资源 ```bash curl -X POST http://localhost/rest-api/index.php \ -H "Content-Type: application/json" \ -d '{"name": "Charlie", "email": "charlie@example.com"}' ``` ### 4. 更新资源 ```bash curl -X PUT http://localhost/rest-api/index.php/3 \ -H "Content-Type: application/json" \ -d '{"name": "Charlie Updated", "email": "charlie.updated@example.com"}' ``` ### 5. 删除资源 ```bash curl -X DELETE http://localhost/rest-api/index.php/2 ``` --- ## 🚀 扩展建议 - 使用真实数据库(如 MySQL、MongoDB)代替内存数组 - 添加身份验证(如 JWT) - 使用路由库(如 Slim Framework、Lumen) - 添加错误日志和异常处理 --- 如果你需要更复杂的版本(比如使用数据库、框架等),欢迎继续提问!
上一篇:
使⽤PHP实现⼀个简单的单例模式
下一篇:
请解释PHP中的异常处理(exception handling),以及如何使⽤ try 、 catch 和 finally 关键字
标题录入,一次不能超过6条
返回顶部
留言
留言
评论