本文目录导读:

- 基础RESTful API示例
- 完整的RESTful API类
- 使用PHP框架创建API(Laravel示例)
- 简单API路由示例
- 使用Slim框架创建API(轻量级)
- API安全考虑
- API版本控制
- 测试API的工具
我来为您详细介绍PHP中如何创建和使用API(应用程序编程接口)。
基础RESTful API示例
GET请求示例
<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
// 模拟数据
$users = [
['id' => 1, 'name' => '张三', 'email' => 'zhangsan@example.com'],
['id' => 2, 'name' => '李四', 'email' => 'lisi@example.com']
];
// 获取请求方法
$method = $_SERVER['REQUEST_METHOD'];
if ($method === 'GET') {
if (isset($_GET['id'])) {
// 获取单个用户
$userId = $_GET['id'];
$user = array_filter($users, fn($u) => $u['id'] == $userId);
echo json_encode(['data' => array_values($user)[0] ?? null]);
} else {
// 获取所有用户
echo json_encode(['data' => $users]);
}
}
?>
POST请求示例(创建数据)
<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, PUT, DELETE');
$method = $_SERVER['REQUEST_METHOD'];
if ($method === 'POST') {
// 获取POST数据
$input = json_decode(file_get_contents('php://input'), true);
if (!$input || !isset($input['name'])) {
http_response_code(400);
echo json_encode(['error' => '缺少必要参数']);
exit;
}
// 处理数据(示例)
$response = [
'success' => true,
'message' => '用户创建成功',
'data' => $input
];
echo json_encode($response);
}
?>
完整的RESTful API类
<?php
class ApiController {
private $db;
public function __construct() {
// 设置头部
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
// 处理预检请求
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
http_response_code(200);
exit();
}
// 数据库连接配置
$this->connectDatabase();
}
private function connectDatabase() {
$host = 'localhost';
$dbname = 'your_database';
$username = 'root';
$password = '';
try {
$this->db = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
$this->sendError(500, '数据库连接失败');
}
}
public function handleRequest() {
$method = $_SERVER['REQUEST_METHOD'];
$uri = $_SERVER['REQUEST_URI'];
// 解析URL路径
$path = parse_url($uri, PHP_URL_PATH);
$pathParts = explode('/', trim($path, '/'));
// 简单路由
$resource = $pathParts[0] ?? '';
$id = $pathParts[1] ?? null;
switch ($method) {
case 'GET':
$this->getResource($resource, $id);
break;
case 'POST':
$this->createResource($resource);
break;
case 'PUT':
$this->updateResource($resource, $id);
break;
case 'DELETE':
$this->deleteResource($resource, $id);
break;
default:
$this->sendError(405, '不允许的请求方法');
}
}
private function getResource($resource, $id) {
if ($id) {
// 获取单个资源
$sql = "SELECT * FROM $resource WHERE id = :id";
$stmt = $this->db->prepare($sql);
$stmt->execute(['id' => $id]);
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$result) {
$this->sendError(404, '资源未找到');
}
$this->sendResponse($result);
} else {
// 获取所有资源
$sql = "SELECT * FROM $resource";
$stmt = $this->db->query($sql);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
$this->sendResponse($results);
}
}
private function createResource($resource) {
$data = json_decode(file_get_contents('php://input'), true);
if (!$data) {
$this->sendError(400, '无效的请求数据');
}
// 构建INSERT语句
$columns = implode(', ', array_keys($data));
$values = ':' . implode(', :', array_keys($data));
$sql = "INSERT INTO $resource ($columns) VALUES ($values)";
$stmt = $this->db->prepare($sql);
if ($stmt->execute($data)) {
$this->sendResponse([
'message' => '创建成功',
'id' => $this->db->lastInsertId()
], 201);
} else {
$this->sendError(500, '创建失败');
}
}
private function updateResource($resource, $id) {
if (!$id) {
$this->sendError(400, '缺少ID参数');
}
$data = json_decode(file_get_contents('php://input'), true);
if (!$data) {
$this->sendError(400, '无效的请求数据');
}
// 构建UPDATE语句
$setClause = [];
foreach ($data as $key => $value) {
$setClause[] = "$key = :$key";
}
$setString = implode(', ', $setClause);
$sql = "UPDATE $resource SET $setString WHERE id = :id";
$data['id'] = $id;
$stmt = $this->db->prepare($sql);
if ($stmt->execute($data)) {
$this->sendResponse(['message' => '更新成功']);
} else {
$this->sendError(500, '更新失败');
}
}
private function deleteResource($resource, $id) {
if (!$id) {
$this->sendError(400, '缺少ID参数');
}
$sql = "DELETE FROM $resource WHERE id = :id";
$stmt = $this->db->prepare($sql);
if ($stmt->execute(['id' => $id])) {
$this->sendResponse(['message' => '删除成功']);
} else {
$this->sendError(500, '删除失败');
}
}
private function sendResponse($data, $statusCode = 200) {
http_response_code($statusCode);
echo json_encode(['success' => true, 'data' => $data]);
exit();
}
private function sendError($statusCode, $message) {
http_response_code($statusCode);
echo json_encode(['success' => false, 'error' => $message]);
exit();
}
}
// 使用示例
$api = new ApiController();
$api->handleRequest();
?>
使用PHP框架创建API(Laravel示例)
// routes/api.php
Route::prefix('v1')->group(function () {
Route::get('/users', 'UserController@index');
Route::get('/users/{id}', 'UserController@show');
Route::post('/users', 'UserController@store');
Route::put('/users/{id}', 'UserController@update');
Route::delete('/users/{id}', 'UserController@destroy');
});
// app/Http/Controllers/UserController.php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
class UserController extends Controller
{
public function index()
{
$users = User::all();
return response()->json(['data' => $users]);
}
public function show($id)
{
$user = User::find($id);
if (!$user) {
return response()->json(['error' => '用户未找到'], 404);
}
return response()->json(['data' => $user]);
}
public function store(Request $request)
{
$validated = $request->validate([
'name' => 'required|string|max:255',
'email' => 'required|email|unique:users'
]);
$user = User::create($validated);
return response()->json(['data' => $user], 201);
}
}
简单API路由示例
<?php
// index.php - 简单的API路由器
$routes = [
'users' => 'UserHandler',
'posts' => 'PostHandler'
];
$uri = $_SERVER['REQUEST_URI'];
$method = $_SERVER['REQUEST_METHOD'];
// 解析路由
$uri = parse_url($uri, PHP_URL_PATH);
$uriParts = explode('/', trim($uri, '/'));
$resource = $uriParts[0] ?? '';
$id = $uriParts[1] ?? null;
if (isset($routes[$resource])) {
$handlerClass = $routes[$resource];
require_once "handlers/{$handlerClass}.php";
$handler = new $handlerClass();
$handler->handle($method, $id);
} else {
http_response_code(404);
echo json_encode(['error' => '路由未找到']);
}
?>
使用Slim框架创建API(轻量级)
<?php
require 'vendor/autoload.php';
use Slim\Factory\AppFactory;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
$app = AppFactory::create();
// GET请求
$app->get('/api/users', function (Request $request, Response $response) {
$users = [
['id' => 1, 'name' => '张三'],
['id' => 2, 'name' => '李四']
];
$payload = json_encode(['data' => $users]);
$response->getBody()->write($payload);
return $response->withHeader('Content-Type', 'application/json');
});
// POST请求
$app->post('/api/users', function (Request $request, Response $response) {
$data = $request->getParsedBody();
$payload = json_encode(['message' => '用户创建成功', 'data' => $data]);
$response->getBody()->write($payload);
return $response
->withHeader('Content-Type', 'application/json')
->withStatus(201);
});
$app->run();
?>
API安全考虑
<?php
// API认证示例
class ApiAuthentication {
// JWT Token验证
public function validateToken($token) {
$secret = 'your-secret-key';
try {
$tokenParts = explode('.', $token);
$header = base64_decode($tokenParts[0]);
$payload = base64_decode($tokenParts[1]);
$signatureProvided = $tokenParts[2];
// 验证签名
$base64UrlHeader = $this->base64UrlEncode($tokenParts[0]);
$base64UrlPayload = $this->base64UrlEncode($tokenParts[1]);
$signature = hash_hmac('sha256',
"$base64UrlHeader.$base64UrlPayload",
$secret,
true
);
$base64UrlSignature = $this->base64UrlEncode($signature);
return $base64UrlSignature === $signatureProvided;
} catch (Exception $e) {
return false;
}
}
private function base64UrlEncode($data) {
return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}
// API密钥验证
public function validateApiKey($apiKey) {
$validKeys = [
'key1' => 'user1',
'key2' => 'user2'
];
return isset($validKeys[$apiKey]);
}
// 速率限制
public function rateLimit($userId) {
$timeLimit = 60; // 60秒
$maxRequests = 10; // 最多请求次数
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$key = "rate_limit:$userId";
$currentCount = $redis->get($key);
if ($currentCount === false) {
$redis->setex($key, $timeLimit, 1);
return true;
}
if ($currentCount >= $maxRequests) {
return false; // 超过限制
}
$redis->incr($key);
return true;
}
}
// 使用中间件进行认证
function authenticate() {
$headers = getallheaders();
// 检查Authorization header
if (!isset($headers['Authorization'])) {
http_response_code(401);
echo json_encode(['error' => '未授权']);
exit();
}
$token = str_replace('Bearer ', '', $headers['Authorization']);
$auth = new ApiAuthentication();
if (!$auth->validateToken($token)) {
http_response_code(401);
echo json_encode(['error' => '无效的token']);
exit();
}
return true;
}
?>
API版本控制
<?php
// API版本控制
class ApiRouter {
public function route() {
$uri = $_SERVER['REQUEST_URI'];
$uriParts = explode('/', trim($uri, '/'));
// 版本号在路径中
$version = $uriParts[0] ?? 'v1';
$resource = $uriParts[1] ?? '';
// 根据版本加载不同处理器
$handlerFile = "api/$version/$resource.php";
if (file_exists($handlerFile)) {
require_once $handlerFile;
$className = ucfirst($resource) . "Controller";
$handler = new $className();
$handler->handle();
} else {
http_response_code(404);
echo json_encode(['error' => 'API版本或资源未找到']);
}
}
}
// 或者在请求头中指定版本
function getApiVersion() {
$headers = getallheaders();
// 检查Accept header
if (isset($headers['Accept'])) {
if (strpos($headers['Accept'], 'application/vnd.api.v2+json') !== false) {
return 'v2';
}
}
// 也可以通过自定义header
if (isset($headers['X-API-Version'])) {
return $headers['X-API-Version'];
}
return 'v1'; // 默认版本
}
?>
测试API的工具
<?php
// 简单的API测试脚本
function testApi() {
$baseUrl = 'http://localhost/api';
// 测试GET请求
$ch = curl_init("$baseUrl/users");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
echo "GET /users - Status: $httpCode\n";
echo "Response: $response\n\n";
// 测试POST请求
$data = json_encode(['name' => 'Test User', 'email' => 'test@example.com']);
$ch = curl_init("$baseUrl/users");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
echo "POST /users - Status: $httpCode\n";
echo "Response: $response\n";
}
testApi();
?>
这些示例涵盖了PHP创建API的常用方法和最佳实践,根据您的具体需求选择合适的方案:
- 小型项目:使用原生PHP或简单路由器
- 中型项目:使用Slim、Laravel Lumen等微框架
- 大型项目:使用完整的Laravel、Symfony框架
记得添加适当的安全措施、错误处理和日志记录!