PHP 函数在构建 RESTful 服务的艺术
在构建 RESTful API 时,PHP 函数扮演着至关重要的角色。通过利用这些函数,您可以轻松处理各种 HTTP 请求,返回格式化的 JSON 响应,并管理状态码。
处理 HTTP 请求
$_SERVER[‘REQUEST_METHOD’]:获取当前请求的方法(GET、POST、PUT、DELETE 等)。file_get_contents(‘php://input’):读取请求体中的 JSON 数据。
生成 JSON 响应
json_encode():将 PHP 数据编码为 JSON 字符串。header(‘Content-Type: application/json’):设置响应标头,指示内容为 JSON。
管理状态码
http_response_code():设置响应的状态码(例如 200、404、500)。exit:停止脚本执行并发送响应。
实战案例
获取所有用户
<?php require ‘connect.php’;// Get all users$sql = "SELECT * FROM users";$result = $conn->query($sql)->fetchAll(PDO::FETCH_ASSOC);// Send JSON responseheader(‘Content-Type: application/json’);echo json_encode($result);?>
创建新用户
<?php require ‘connect.php’;// Decode request JSON data$data = json_decode(file_get_contents(‘php://input’), true);// Create new user$name = $data[‘name’];$age = $data[‘age’];$stmt = $conn->prepare("INSERT INTO users (name, age) VALUES (?, ?)");$stmt->execute([$name, $age]);// Get new user ID$id = $conn->lastInsertId();// Send JSON responseheader(‘Content-Type: application/json’);echo json_encode([‘id’ => $id]);?>
更新用户
<?php require ‘connect.php’;// Decode request JSON data$data = json_decode(file_get_contents(‘php://input’), true);// Update user$id = $data[‘id’];$name = $data[‘name’];$age = $data[‘age’];$stmt = $conn->prepare("UPDATE users SET name = ?, age = ? WHERE id = ?");$stmt->execute([$name, $age, $id]);// Send JSON responseheader(‘Content-Type: application/json’);echo json_encode([‘success’ => true]);?>
删除用户
<?php require ‘connect.php’;// Decode request JSON data$data = json_decode(file_get_contents(‘php://input’), true);// Delete user$id = $data[‘id’];$stmt = $conn->prepare("DELETE FROM users WHERE id = ?");$stmt->execute([$id]);// Send JSON responseheader(‘Content-Type: application/json’);echo json_encode([‘success’ => true]);?>
以上就是PHP函数在构建RESTful服务的艺术的详细内容,更多请关注范的资源库其它相关文章!
转载请注明:范的资源库 » PHP函数在构建RESTful服务的艺术