用PHP创建代理服务器
当你在编写PHP代码的时候,会有一种想要编写代理服务器的冲动,对吗?
需要使用 composer 来安装 guzzlehttp/guzzle。
<?php
namespace zonuexe\ZoProxy;
use GuzzleHttp\Client as HttpClient;
use GuzzleHttp\Psr7;
require __DIR__ . '/../vendor/autoload.php';
// ここはいい感じにやってね
$host_table = [
'hoge.example.com' => [
'host' => 'localhost',
'port' => 3939,
'scheme' => 'http',
],
'foo.example.com' => [
'host' => 'foo.example.jp',
'scheme' => 'https',
],
];
$request = Psr7\ServerRequest::fromGlobals();
$new_uri = $request->getUri()->withPort(80);
$key = $new_uri->getHost();
$port = $new_uri->getPort();
if ($port !== null && !Psr7\Uri::isDefaultPort($port)) {
$key .= ":{$port}";
}
if (isset($host_table[$key])) {
if (isset($host_table[$key]['host'])) {
$new_uri = $new_uri->withHost($host_table[$key]['host']);
}
if (isset($host_table[$key]['port'])) {
$new_uri = $new_uri->withPort($host_table[$key]['port']);
}
if (isset($host_table[$key]['scheme'])) {
$new_uri = $new_uri->withScheme($host_table[$key]['scheme']);
}
}
$client = new HttpClient;
$response = $client->send($request->withUri($new_uri), [
'http_errors' => false,
]);
foreach ($response->getHeaders() as $key => $values) {
foreach ($values as $value) {
header("{$key}:{$value}");
}
}
echo $response->getBody();
我觉得如果按照普通的方式做,不会再更容易了,所以著作权之类的无需特别在意,随意复制粘贴即可。
这有什么用处?
A. 好吧… 我写完这个之后在工作中经常使用它。
作为一个例子,在共享的开发服务器上,其中运行着Apache的PHP5系列(端口为80),我们可以使用命令 php -S localhost:3939 来启动PHP 7.1的内置服务器,并将其代理到这个端口。
因为我没有改变HTTP的Host,所以在我这种情况下是很方便的,但可能会有很多问题,所以请根据情况自行处理。