当前位置:首页 > PHP

php实现代理服务器

2026-01-29 07:56:07PHP

实现 PHP 代理服务器的基本方法

PHP 可以通过流上下文(Stream Context)或 cURL 扩展实现代理服务器功能。以下是两种常见实现方式:

使用 stream_context_create 实现

通过 PHP 内置的流功能创建代理请求:

<?php
$targetUrl = $_GET['url'] ?? '';
if (empty($targetUrl)) {
    die('Missing URL parameter');
}

$context = stream_context_create([
    'http' => [
        'method' => $_SERVER['REQUEST_METHOD'],
        'header' => getallheaders(),
        'ignore_errors' => true
    ]
]);

$response = file_get_contents($targetUrl, false, $context);
header('Content-Type: ' . $http_response_header[0]);
echo $response;
?>

使用 cURL 扩展实现

更强大的代理实现方式,支持更多协议和选项:

<?php
$targetUrl = $_GET['url'] ?? '';
if (empty($targetUrl)) {
    die('Missing URL parameter');
}

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $targetUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HEADER, true);

// 传递原始请求头
$headers = [];
foreach (getallheaders() as $name => $value) {
    $headers[] = "$name: $value";
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$response = curl_exec($ch);
$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$headers = substr($response, 0, $headerSize);
$body = substr($response, $headerSize);

// 转发响应头
foreach (explode("\r\n", $headers) as $header) {
    if (!empty($header)) {
        header($header);
    }
}

echo $body;
curl_close($ch);
?>

安全性注意事项

实现代理服务器时需要考虑以下安全措施:

验证目标URL,防止SSRF攻击:

$allowedDomains = ['example.com', 'trusted-site.com'];
$parsedUrl = parse_url($targetUrl);
if (!in_array($parsedUrl['host'], $allowedDomains)) {
    die('Access to this domain is not allowed');
}

限制请求大小防止滥用:

$maxSize = 1024 * 1024; // 1MB
if (strlen($response) > $maxSize) {
    die('Response too large');
}

性能优化建议

对于高频使用的代理服务器,可以考虑以下优化:

启用缓存减少重复请求:

$cacheKey = md5($targetUrl);
$cacheFile = "/tmp/proxy_cache_$cacheKey";

if (file_exists($cacheFile) && (time() - filemtime($cacheFile) < 3600)) {
    readfile($cacheFile);
    exit;
}

// ...处理请求...

file_put_contents($cacheFile, $response);

使用连接池保持持久连接:

curl_setopt($ch, CURLOPT_FORBID_REUSE, false);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, false);

完整代理服务器示例

结合上述技术的完整实现:

<?php
// 安全配置
$allowedDomains = ['example.com', 'trusted-site.com'];
$maxSize = 1024 * 1024; // 1MB

// 获取目标URL
$targetUrl = $_GET['url'] ?? '';
if (empty($targetUrl)) {
    http_response_code(400);
    die('Missing URL parameter');
}

// 验证目标域名
$parsedUrl = parse_url($targetUrl);
if (!isset($parsedUrl['host']) || !in_array($parsedUrl['host'], $allowedDomains)) {
    http_response_code(403);
    die('Access to this domain is not allowed');
}

// 初始化cURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $targetUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HEADER, true);

// 传递请求头
$headers = [];
foreach (getallheaders() as $name => $value) {
    if (strtolower($name) !== 'host') { // 排除Host头
        $headers[] = "$name: $value";
    }
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

// 执行请求
$response = curl_exec($ch);
if (strlen($response) > $maxSize) {
    http_response_code(413);
    die('Response too large');
}

// 处理响应
$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$headers = substr($response, 0, $headerSize);
$body = substr($response, $headerSize);

// 转发响应头
foreach (explode("\r\n", $headers) as $header) {
    if (!empty($header)) {
        header($header);
    }
}

echo $body;
curl_close($ch);
?>

以上代码提供了PHP实现代理服务器的基本框架,可根据实际需求进行调整和扩展。

php实现代理服务器

分享给朋友:

相关文章

php实现分页

php实现分页

PHP实现分页的基本方法 使用LIMIT和OFFSET进行数据库查询分页。通过计算当前页码和每页显示数量,动态生成SQL语句。 $page = isset($_GET['page']) ? (in…

git php实现

git php实现

Git 与 PHP 的集成实现 使用 PHP 执行 Git 命令 通过 PHP 的 exec()、shell_exec() 或 passthru() 函数可以直接调用 Git 命令,适用于服务器端操作…

php实现定时任务

php实现定时任务

PHP 实现定时任务的几种方法 在 PHP 中实现定时任务可以通过多种方式完成,具体选择取决于项目需求和服务器环境。以下是常见的实现方法: 使用 Cron 任务 Cron 是 Linux 系统中常用…

php实现表单

php实现表单

PHP 表单基础实现 创建一个简单的 PHP 表单需要 HTML 表单结构和 PHP 处理脚本。以下是一个完整的示例: HTML 表单部分 (form.html) <form actio…

php实现队列

php实现队列

PHP实现队列的方法 队列是一种先进先出(FIFO)的数据结构,PHP可以通过多种方式实现队列功能。 使用数组模拟队列 PHP数组可以模拟队列的基本操作,通过array_push和array_shi…

php实现

php实现

PHP 实现的基本方法 PHP 是一种服务器端脚本语言,广泛用于 Web 开发。以下是 PHP 实现的一些常见方法。 变量与数据类型 PHP 变量以 $ 开头,支持多种数据类型: $nam…