本站资源收集于互联网,不提供软件存储服务,每天免费更新优质的软件以及学习资源!

PHP函数在构建RESTful服务的艺术

网络教程 app 1℃

PHP函数在构建RESTful服务的艺术

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)-&gt;fetchAll(PDO::FETCH_ASSOC);// Send JSON responseheader(‘Content-Type: application/json’);echo json_encode($result);?&gt;

创建新用户

<?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-&gt;execute([$name, $age]);// Get new user ID$id = $conn-&gt;lastInsertId();// Send JSON responseheader(‘Content-Type: application/json’);echo json_encode([‘id’ =&gt; $id]);?&gt;

更新用户

<?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-&gt;execute([$name, $age, $id]);// Send JSON responseheader(‘Content-Type: application/json’);echo json_encode([‘success’ =&gt; true]);?&gt;

删除用户

<?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-&gt;execute([$id]);// Send JSON responseheader(‘Content-Type: application/json’);echo json_encode([‘success’ =&gt; true]);?&gt;

以上就是PHP函数在构建RESTful服务的艺术的详细内容,更多请关注范的资源库其它相关文章!

转载请注明:范的资源库 » PHP函数在构建RESTful服务的艺术

喜欢 (0)