HTTP狀態碼是客戶端與服務端溝通的標準語言。本文提供完整標準狀態碼映射表、PHPheader()發送封裝函數、RESTful API常用碼選擇指南、自定義錯誤頁面配置。
<?php
class HttpStatus {
public const CONTINUE = 100;
public const SWITCHING_PROTOCOLS = 101;
public const PROCESSING = 102;
public const OK = 200;
public const CREATED = 201;
public const ACCEPTED = 202;
public const NON_AUTHORITATIVE_INFORMATION = 203;
public const NO_CONTENT = 204;
public const RESET_CONTENT = 205;
public const PARTIAL_CONTENT = 206;
public const MULTI_STATUS = 207;
public const ALREADY_REPORTED = 208;
public const IM_USED = 226;
public const MULTIPLE_CHOICES = 300;
public const MOVED_PERMANENTLY = 301;
public const FOUND = 302;
public const SEE_OTHER = 303;
public const NOT_MODIFIED = 304;
public const USE_PROXY = 305;
public const TEMPORARY_REDIRECT = 307;
public const PERMANENT_REDIRECT = 308;
public const BAD_REQUEST = 400;
public const UNAUTHORIZED = 401;
public const PAYMENT_REQUIRED = 402;
public const FORBIDDEN = 403;
public const NOT_FOUND = 404;
public const METHOD_NOT_ALLOWED = 405;
public const NOT_ACCEPTABLE = 406;
public const PROXY_AUTHENTICATION_REQUIRED = 407;
public const REQUEST_TIMEOUT = 408;
public const CONFLICT = 409;
public const GONE = 410;
public const LENGTH_REQUIRED = 411;
public const PRECONDITION_FAILED = 412;
public const CONTENT_TOO_LARGE = 413;
public const URI_TOO_LONG = 414;
public const UNSUPPORTED_MEDIA_TYPE = 415;
public const RANGE_NOT_SATISFIABLE = 416;
public const EXPECTATION_FAILED = 417;
public const IM_A_TEAPOT = 418;
public const MISDIRECTED_REQUEST = 421;
public const UNPROCESSABLE_CONTENT = 422;
public const LOCKED = 423;
public const FAILED_DEPENDENCY = 424;
public const TOO_EARLY = 425;
public const UPGRADE_REQUIRED = 426;
public const PRECONDITION_REQUIRED = 428;
public const TOO_MANY_REQUESTS = 429;
public const REQUEST_HEADER_FIELDS_TOO_LARGE = 431;
public const UNAVAILABLE_FOR_LEGAL_REASONS = 451;
public const INTERNAL_SERVER_ERROR = 500;
public const NOT_IMPLEMENTED = 501;
public const BAD_GATEWAY = 502;
public const SERVICE_UNAVAILABLE = 503;
public const GATEWAY_TIMEOUT = 504;
public const HTTP_VERSION_NOT_SUPPORTED = 505;
public const VARIANT_ALSO_NEGOTIATES = 506;
public const INSUFFICIENT_STORAGE = 507;
public const LOOP_DETECTED = 508;
public const NOT_EXTENDED = 510;
public const NETWORK_AUTHENTICATION_REQUIRED = 511;
public static function send(int $code, string $protocol = 'HTTP/1.1'): void {
$text = self::getReasonPhrase($code);
header("$protocol $code $text", true, $code);
}
public static function getReasonPhrase(int $code): string {
return self::$phrases[$code] ?? 'Unknown Status';
}
// $phrases 數組略(包含所有上述碼的標準原因短語)
}
| 場景 | 狀態碼 | 說明 |
|---|---|---|
| 成功獲取資源 | 200 OK | GET/HEAD成功 |
| 資源創建成功 | 201 Created | POST創建,返回Location頭 |
| 異步任務已受理 | 202 Accepted | 返回任務ID供輪詢 |
| 成功無內容返回 | 204 No Content | DELETE/PUT成功無響應體 |
| 客戶端錯誤:參數校驗失敗 | 400 Bad Request | 附帶詳細錯誤信息 |
| 未認證/Token失效 | 401 Unauthorized | 附帶WWW-Authenticate |
| 無權限 | 403 Forbidden | 認證通過但授權失敗 |
| 資源不存在 | 404 Not Found | |
| 方法不允許 | 405 Method Not Allowed | 附帶Allow頭 |
| 衝突(如唯一鍵重複) | 409 Conflict | |
| 頻率限制 | 429 Too Many Requests | 附帶Retry-After |
| 服務器內部錯誤 | 500 Internal Server Error | 記錄詳情,不暴露給客戶端 |
| 服務不可用(維護/過載) | 503 Service Unavailable | 附帶Retry-After |
// 1. 必須在任何輸出前調用
HttpStatus::send(HttpStatus::CREATED);
// 2. 配合JSON錯誤格式(RFC 7807 Problem Details)
header('Content-Type: application/problem+json; charset=utf-8');
echo json_encode([
'type' => 'https://example.com/probs/validation-failed',
'title' => 'Validation Failed',
'status' => 400,
'detail' => 'email 欄位格式不正確',
'instance' => '/api/users',
'errors' => ['email' => ['格式不正確']],
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
# Nginx
error_page 404 /errors/404.html;
error_page 500 502 503 504 /errors/50x.html;
location /errors/ { internal; }
統一使用常量類管理狀態碼,避免魔術數字,提升代碼可讀性與維護性。