nahid/request-proxy

请求代理库可以帮助您将请求代理到其他服务器

dev-master 2023-04-04 06:57 UTC

This package is auto-updated.

Last update: 2024-09-04 10:24:48 UTC


README

此包是从 jenssegers/php-proxy 分支出来的,并进行了修改。它与原始包不兼容。基本上原始包不再维护,因此我创建了分支。

这是一个 HTTP/HTTPS 代理脚本,将请求转发到不同的服务器并返回响应。Proxy 类使用 PSR7 请求/响应对象作为输入/输出,并使用 Guzzle 进行实际的 HTTP 请求。

安装

使用 composer 安装

composer require nahid/request-proxy

示例

以下示例创建了一个基于当前浏览器请求的请求对象,并将其转发到 example.comRemoveEncodingFilter 从原始响应中删除编码头,以便当前 web 服务器可以正确设置这些。

use Nahid\RequestProxy\Proxy;
use Nahid\RequestProxy\Adapter\Guzzle\GuzzleAdapter;
use Nahid\RequestProxy\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');