spatie / guzzle-redirect-history-middleware
用于跟踪重定向的 Guzzle 中间件
Requires
- php: ^8.0
- guzzlehttp/guzzle: ^7.2
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.0
- pestphp/pest: ^1.20
- spatie/ray: ^1.28
- vimeo/psalm: ^4.8
README
用于跟踪重定向的 Guzzle 中间件
本包包含用于 Guzzle 的中间件,允许您跟踪请求期间发生的重定向。
支持我们
我们投入大量资源创建 最佳开源包。您可以通过 购买我们的付费产品之一 来支持我们。
我们非常感谢您从家乡寄来明信片,提及您正在使用我们哪个包。您可以在 我们的联系页面 上找到我们的地址。我们将所有收到的明信片发布在 我们的虚拟明信片墙上。
安装
您可以通过 composer 安装此包
composer require spatie/guzzle-redirect-history-middleware
使用方法
以下是如何使用 Spatie\GuzzleRedirectHistoryMiddleware\RedirectHistoryMiddleware
将重定向历史存储在 Spatie\GuzzleRedirectHistoryMiddleware\RedirectHistory
实例中的快速示例。
use Spatie\GuzzleRedirectHistoryMiddleware\RedirectHistory; use Spatie\GuzzleRedirectHistoryMiddleware\RedirectHistoryMiddleware; /* * First create a new instance of `RedirectHistory` * This instance can be used after the requests to get the redirects. */ $redirectHistory = new RedirectHistory(); /* * This is the default way to add a middleware to Guzzle * default middleware stack. */ $stack = HandlerStack::create(); $stack->push(RedirectHistoryMiddleware::make($redirectHistory)); /* * Let's create Guzzle client that uses the middleware stack * containing our `RedirectHistoryMiddleware`. */ $client = new Client([ 'handler' => $stack, ]); /* * Now, let's make a request. */ $response = $client->get($anyUrl); /* * And tada, here are all the redirects performed * during the request. */ $redirects = $redirectHistory->toArray();
$redirects
是一个数组,其元素是一个包含以下键的数组
status
: 响应的状态码url
: 导致重定向的请求的 URL
所以如果您请求 https://example.com/page-a
,该请求重定向到 /page-b
,最终重定向到 /page-c
,这将 $redirects
的内容
[ ['status' => 302, 'url' => 'https://example.com/page-a'], ['status' => 302, 'url' => 'https://example.com/page-b'], ['status' => 200, 'url' => 'https://example.com/page-c'], ];
即使您的初始请求导致 \GuzzleHttp\Exception\TooManyRedirectsException
,RedirectHistory
仍然包含执行的重定向
我们创建此包的原因
Guzzle 有 内置的重定向跟踪支持。不幸的是,它并不是那么适合开发者使用。您必须操作和组合在 X-Guzzle-Redirect-History
和 X-Guzzle-Redirect-Status-History
标头中找到的数组。
此外,当遇到异常,如 TooManyRedirectsException
时,这些标头不会被填充。
我们的包使检索重定向变得容易。即使请求最终失败,您也能够获取重定向历史。
测试
composer test
变更日志
有关最近更改的更多信息,请参阅 变更日志。
贡献
有关详细信息,请参阅 贡献指南。
安全漏洞
请参阅 我们的安全策略 了解如何报告安全漏洞。
鸣谢
许可协议
MIT 许可证 (MIT)。有关更多信息,请参阅 许可文件。