php 实现转发

PHP 实现 HTTP 转发
使用 PHP 实现 HTTP 请求转发可以通过 cURL 或 file_get_contents 完成。以下是两种常见方法:
使用 cURL 转发请求
$targetUrl = 'https://example.com/api'; // 目标地址
$ch = curl_init($targetUrl);
// 设置请求方法(GET/POST等)
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $_SERVER['REQUEST_METHOD']);
// 转发原始请求头(可选)
$headers = [];
foreach (getallheaders() as $name => $value) {
$headers[] = "$name: $value";
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// 转发请求体(POST/PUT等)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents('php://input'));
}
// 返回响应给客户端
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
// 输出响应
header('Content-Type: application/json');
echo $response;
使用 file_get_contents 转发 GET 请求
$targetUrl = 'https://example.com/api?' . http_build_query($_GET);
$context = stream_context_create([
'http' => [
'method' => 'GET',
'header' => implode("\r\n", array_map(
function ($k, $v) { return "$k: $v"; },
array_keys(getallheaders()),
array_values(getallheaders())
))
]
]);
$response = file_get_contents($targetUrl, false, $context);
header('Content-Type: application/json');
echo $response;
注意事项
- 对于 HTTPS 目标地址,需确保服务器支持 SSL 证书验证(可添加
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false)跳过验证,但生产环境不推荐) - 转发敏感数据时需考虑安全性,建议添加身份验证或 IP 白名单
- 大文件上传需调整 PHP 的
memory_limit和post_max_size配置
反向代理实现
如需实现更完整的反向代理功能(如保留原始 URL 路径),可通过解析 $_SERVER['REQUEST_URI'] 动态拼接目标地址:
$baseUrl = 'https://example.com';
$targetUrl = $baseUrl . $_SERVER['REQUEST_URI'];
// 其余转发逻辑同上







