itsmill3rtime / proxy
此包的最新版本(v3.1.1)没有提供许可证信息。
代理库,将请求转发到指定的URL并返回响应。
v3.1.1
2022-07-21 23:30 UTC
Requires
- php: *
- guzzlehttp/guzzle: ^7.2
- laminas/laminas-diactoros: ^2.0
- laminas/laminas-httphandlerrunner: ^1.1
- psr/http-message: ^1.0
- relay/relay: ^1.0
Requires (Dev)
- mockery/mockery: ^1.1
- php-coveralls/php-coveralls: ^2.0
- phpunit/phpunit: ^5.0|^6.0|^7.0
This package is auto-updated.
Last update: 2024-09-22 03:49:19 UTC
README
这是一个 HTTP/HTTPS 代理脚本,将请求转发到不同的服务器并返回响应。Proxy 类使用 PSR7 请求/响应对象作为输入/输出,并使用 Guzzle 执行实际的 HTTP 请求。
安装
使用 composer 安装
composer require jenssegers/proxy
示例
以下示例创建了一个基于当前浏览器请求的请求对象,并将其转发到 example.com
。RemoveEncodingFilter
移除了原始响应的编码头,以便当前 Web 服务器可以正确设置这些头。
use Proxy\Proxy; use Proxy\Adapter\Guzzle\GuzzleAdapter; use Proxy\Filter\RemoveEncodingFilter; use Laminas\Diactoros\ServerRequestFactory; // Create a PSR7 request based on the current browser request. $request = ServerRequestFactory::fromGlobals(); // Create a guzzle client $guzzle = new GuzzleHttp\Client(); // Create the proxy instance $proxy = new Proxy(new GuzzleAdapter($guzzle)); // Add a response filter that removes the encoding headers. $proxy->filter(new RemoveEncodingFilter()); try { // Forward the request and get the response. $response = $proxy->forward($request)->to('http://example.com'); // Output response to the browser. (new Laminas\HttpHandlerRunner\Emitter\SapiEmitter)->emit($response); } catch(\GuzzleHttp\Exception\BadResponseException $e) { // Correct way to handle bad responses (new Laminas\HttpHandlerRunner\Emitter\SapiEmitter)->emit($e->getResponse()); }
过滤器
您可以使用中间件策略对请求和响应应用过滤器
$response = $proxy ->forward($request) ->filter(function ($request, $response, $next) { // Manipulate the request object. $request = $request->withHeader('User-Agent', 'FishBot/1.0'); // Call the next item in the middleware. $response = $next($request, $response); // Manipulate the response object. $response = $response->withHeader('X-Proxy-Foo', 'Bar'); return $response; }) ->to('http://example.com');