php实现代理
PHP实现HTTP代理
使用PHP实现HTTP代理可以通过以下方法完成。这里提供一个简单的代理脚本示例,能够转发HTTP请求到目标服务器并返回响应。
基础代理实现
<?php
// 获取目标URL
$url = isset($_GET['url']) ? $_GET['url'] : '';
if (empty($url)) {
header('HTTP/1.1 400 Bad Request');
echo 'Missing URL parameter';
exit;
}
// 初始化cURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HEADER, true);
// 转发请求头
$headers = array();
foreach (getallheaders() as $name => $value) {
if (strtolower($name) !== 'host') {
$headers[] = "$name: $value";
}
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// 执行请求
$response = curl_exec($ch);
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$headers = substr($response, 0, $header_size);
$body = substr($response, $header_size);
// 返回响应头
foreach (explode("\r\n", $headers) as $header) {
if (!empty($header)) {
header($header);
}
}
// 返回响应体
echo $body;
curl_close($ch);
?>
安全性增强
为代理添加基本的安全措施:

// 允许的域名白名单
$allowedDomains = array(
'example.com',
'api.example.org'
);
$parsedUrl = parse_url($url);
if (!in_array($parsedUrl['host'], $allowedDomains)) {
header('HTTP/1.1 403 Forbidden');
echo 'Access to this domain is not allowed';
exit;
}
// 限制请求方法
$allowedMethods = array('GET', 'POST');
$method = $_SERVER['REQUEST_METHOD'];
if (!in_array($method, $allowedMethods)) {
header('HTTP/1.1 405 Method Not Allowed');
echo 'Method not allowed';
exit;
}
POST请求处理
处理POST请求需要额外配置:

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$postData = file_get_contents('php://input');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
// 设置Content-Type
$contentType = isset($_SERVER['CONTENT_TYPE']) ? $_SERVER['CONTENT_TYPE'] : '';
if (!empty($contentType)) {
curl_setopt($ch, CURLOPT_HTTPHEADER, array_merge($headers, array("Content-Type: $contentType")));
}
}
性能优化
添加缓存机制提高性能:
// 缓存设置
$cacheDir = __DIR__ . '/cache/';
$cacheTime = 3600; // 1小时
$cacheKey = md5($url);
$cacheFile = $cacheDir . $cacheKey;
// 检查缓存
if (file_exists($cacheFile) && (time() - filemtime($cacheFile)) < $cacheTime) {
readfile($cacheFile);
exit;
}
// 执行请求后缓存结果
file_put_contents($cacheFile, $response);
使用示例
客户端调用代理:
fetch('/proxy.php?url=https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data));
注意事项
- 代理服务器可能成为攻击目标,应实施严格的安全措施
- 高流量场景下需要考虑性能优化和负载均衡
- 某些网站可能检测并阻止代理请求
- 遵守目标网站的服务条款和robots.txt规定
以上代码提供了PHP实现HTTP代理的基本框架,可根据实际需求进行扩展和优化。






