php实现http协议
PHP 实现 HTTP 协议
使用内置函数发送 HTTP 请求
PHP 提供 file_get_contents 和 stream_context_create 函数组合实现简单的 HTTP 请求:
$url = 'http://example.com/api';
$options = [
'http' => [
'method' => 'POST',
'header' => 'Content-type: application/json',
'content' => json_encode(['key' => 'value'])
]
];
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
通过 cURL 扩展实现
cURL 是更强大的 HTTP 客户端解决方案:
$ch = curl_init('http://example.com/api');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, ['key' => 'value']);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json'
]);
$response = curl_exec($ch);
curl_close($ch);
创建 HTTP 服务器
使用内置的 php -S 命令启动开发服务器:
php -S localhost:8000
实现基础 HTTP 服务器
通过 socket 编程创建原始 HTTP 服务器:
$socket = stream_socket_server("tcp://0.0.0.0:8080", $errno, $errstr);
if (!$socket) {
die("$errstr ($errno)");
}
while ($conn = stream_socket_accept($socket)) {
$request = fread($conn, 1024);
$response = "HTTP/1.1 200 OK\r\n"
. "Content-Type: text/plain\r\n"
. "\r\n"
. "Hello World";
fwrite($conn, $response);
fclose($conn);
}
fclose($socket);
处理 HTTP 请求头
解析接收到的 HTTP 请求头:
$headers = [];
foreach ($_SERVER as $key => $value) {
if (strpos($key, 'HTTP_') === 0) {
$headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($key, 5)))))] = $value;
}
}
发送自定义 HTTP 响应
设置完整的 HTTP 响应头和状态码:

header('HTTP/1.1 201 Created');
header('Content-Type: application/json');
header('X-Custom-Header: Value');
echo json_encode(['status' => 'success']);
处理文件上传
接收 multipart/form-data 类型的文件上传:
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file'])) {
$uploadDir = 'uploads/';
$uploadFile = $uploadDir . basename($_FILES['file']['name']);
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile)) {
http_response_code(200);
echo 'File uploaded';
} else {
http_response_code(500);
echo 'Upload failed';
}
}
处理重定向
实现 301/302 重定向:
header('Location: https://newlocation.com', true, 301);
exit;
处理 Cookie
设置和读取 HTTP Cookie:

// 设置 Cookie
setcookie('user', 'john', time() + 3600, '/', 'example.com', true, true);
// 读取 Cookie
$user = $_COOKIE['user'] ?? 'guest';
处理 HTTPS
强制 HTTPS 连接:
if (empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] === 'off') {
$redirect = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
header('HTTP/1.1 301 Moved Permanently');
header('Location: ' . $redirect);
exit;
}
处理 RESTful API
实现简单的 REST API 路由:
$method = $_SERVER['REQUEST_METHOD'];
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
switch ($method) {
case 'GET':
if ($path === '/users') {
// 返回用户列表
}
break;
case 'POST':
if ($path === '/users') {
// 创建新用户
}
break;
}
性能优化
启用输出缓冲和压缩:
ob_start('ob_gzhandler');
// 页面内容
ob_end_flush();
调试 HTTP 请求
记录完整的 HTTP 请求信息:
file_put_contents('request.log', print_r($_SERVER, true) . print_r($_POST, true) . print_r($_GET, true));






