萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 基於 cURL 實現 RESTful API 服務端與客戶端完整架構

PHP cURL 實戰:構建跨平台 RESTful API 服務端與客戶端

RESTful API 是現代微服務架構的標準協議。本文提供基於 PHP cURL 擴展的完整服務端路由分發架構與客戶端封裝類,支持標準 HTTP 動詞、資源導向設計、Token 驗證、統一響應格式。

服務端核心架構:ApiServer 類

<?php
class ApiServer {
    private $method = '';
    protected $params = [];
    protected $resource = '';
    protected $resourceId = null;
    
    public function __construct() {
        $this->authorize();           // 1. 驗證簽名
        $this->method = strtolower($_SERVER['REQUEST_METHOD']);
        $this->parseResource();       // 2. 解析資源路徑
        $this->parseParams();         // 3. 解析請求參數
        $this->dispatch();            // 4. 分發處理
    }
    
    // 驗證簽名認證
    private function authorize() {
        $token = $_SERVER['HTTP_CLIENT_TOKEN'] ?? '';
        $sign = $_SERVER['HTTP_CLIENT_CODE'] ?? '';
        $expected = md5(substr(md5($token), 8, 24) . $token);
        
        if ($sign !== $expected) {
            $this->respond(401, 'Unauthorized: Invalid signature');
        }
    }
    
    // RESTful 路由解析: /users/123 → resource=users, id=123
    private function parseResource() {
        $pathinfo = $_SERVER['PATH_INFO'] ?? '/';
        $parts = array_filter(explode('/', trim($pathinfo, '/')));
        $this->resource = $parts[0] ?? '';
        $this->resourceId = $parts[1] ?? null;
    }
    
    // 統一參數獲取 (GET/POST/PUT/DELETE 統一從 $_GET 獲取,實際項目建議解析 php://input)
    private function parseParams() {
        $this->params = $_GET; // 簡化演示
    }
    
    // 動作分發
    private function dispatch() {
        $method = '_' . $this->method;
        if (method_exists($this, $method)) {
            $this->$method();
        } else {
            $this->respond(405, 'Method Not Allowed');
        }
    }
    
    // 統一響應格式
    protected function respond(int $code, mixed $data = null, string $message = '') {
        http_response_code($code);
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode([
            'code' => $code,
            'message' => $message ?: ($code === 200 ? 'Success' : 'Error'),
            'data' => $data,
            'timestamp' => time()
        ], JSON_UNESCAPED_UNICODE);
        exit;
    }
    
    // 子類實現具體業務
    protected function _get() { $this->respond(200, ['resource' => $this->resource]); }
    protected function _post() { $this->respond(201, ['created' => true]); }
    protected function _put() { $this->respond(200, ['updated' => true]); }
    protected function _delete() { $this->respond(200, ['deleted' => true]); }
}

// 入口文件
$api = new ApiServer();
?>

路由映射規範

HTTP 方法路徑模式語義處理方法
GET/users列表查詢_get()
POST/users創建資源_post()
GET/users/{id}單條詳情_get()
PUT/users/{id}全量更新_put()
PATCH/users/{id}部分更新_patch()
DELETE/users/{id}刪除資源_delete()

客戶端封裝:RestClient 類

<?php
class RestClient {
    private $baseUrl;
    private $token;
    private $timeout = 30;
    
    public function __construct(string $baseUrl, string $token) {
        $this->baseUrl = rtrim($baseUrl, '/');
        $this->token = $token;
    }
    
    public function request(string $method, string $resource, ?int $id = null, array $data = []): array {
        $url = $this->baseUrl . '/' . ltrim($resource, '/');
        if ($id !== null) $url .= '/' . $id;
        
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_CUSTOMREQUEST => strtoupper($method),
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => $this->timeout,
            CURLOPT_HTTPHEADER => [
                'Content-Type: application/json',
                'Client-Token: ' . $this->token,
                'Client-Code: ' . $this->generateSign($this->token),
            ],
        ]);
        
        if (in_array($method, ['post', 'put', 'patch'])) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        } elseif ($method === 'get' && $data) {
            $url .= '?' . http_build_query($data);
            curl_setopt($ch, CURLOPT_URL, $url);
        }
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        curl_close($ch);
        
        if ($error) throw new RuntimeException("cURL Error: $error");
        
        $result = json_decode($response, true);
        if ($httpCode >= 400) {
            throw new RuntimeException("API Error [$httpCode]: " . ($result['message'] ?? 'Unknown'));
        }
        
        return $result['data'] ?? [];
    }
    
    private function generateSign(string $token): string {
        return md5(substr(md5($token), 8, 24) . $token);
    }
    
    // 便捷方法
    public function get(string $resource, ?int $id = null, array $query = []) { return $this->request('get', $resource, $id, $query); }
    public function post(string $resource, array $data) { return $this->request('post', $resource, null, $data); }
    public function put(string $resource, int $id, array $data) { return $this->request('put', $resource, $id, $data); }
    public function delete(string $resource, int $id) { return $this->request('delete', $resource, $id); }
}

// 使用示例
$client = new RestClient('https://api.example.com', 'your_secret_token');
$users = $client->get('users');
$user = $client->get('users', 123);
$newUser = $client->post('users', ['name' => 'John', 'email' => 'john@example.com']);
$client->put('users', 123, ['name' => 'John Updated']);
$client->delete('users', 123);
?>

安全增強建議

  1. HTTPS 強制:生產環境必須啟用 TLS 1.2+
  2. 簽名算法升級:使用 HMAC-SHA256 替代 MD5,添加時間戳防重放
  3. 限流熔斷:客戶端集成令牌桶限流,服務端接入 Sentinel/RateLimiter
  4. 請求驗證:服務端使用 JSON Schema 驗證輸入參數
  5. 審計日誌:記錄所有 API 調用:請求 ID、用戶、IP、耗時、響應碼

Nginx 反向代理配置關鍵

location /api/ {
    # 必須傳遞 PATH_INFO 給 PHP
    fastcgi_split_path_info ^(/api)(.*)$;
    fastcgi_param PATH_INFO $fastcgi_path_info;
    
    fastcgi_pass unix:/run/php/php8.2-fpm.sock;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root/api/index.php;
}
copyright © 萬盛學電腦網 all rights reserved