kelvinzer0 / curl-impersonate-php
Curl-Impersonate-PHP - 一个使用cURL在PHP环境中执行HTTP请求的库,具有模拟主流浏览器(Chrome、Firefox、Safari和Microsoft Edge)行为的能力。
Requires
- php: >=5.4.0
This package is not auto-updated.
Last update: 2024-09-17 14:30:37 UTC
README
Curl-Impersonate-PHP是一个库,允许在PHP环境中使用cURL执行HTTP请求,并具有模拟四个主要浏览器(Chrome、Firefox、Safari和Microsoft Edge)行为的能力。
描述
Curl-Impersonate-PHP是原始项目Curl-Impersonate(可在https://github.com/lwthiker/curl-impersonate找到)的一个实现,该项目引入了一个专门的cURL构建,可以模仿四个主要浏览器的行为。通过使用Curl-Impersonate-PHP,您可以使用cURL从PHP中发送HTTP请求,但使用类似于Chrome、Firefox、Safari或Microsoft Edge的头部和行为。
关键特性
- 支持使用cURL通过头部和行为模拟Chrome、Firefox、Safari和Microsoft Edge进行HTTP请求。
- 通过
setopt
函数完全控制cURL选项,如目标URL、HTTP方法、请求数据、头部等。 - 能够以cURL命令、标准输出或流的形式访问请求的执行结果。
安装
您可以使用Composer安装Curl-Impersonate-PHP。在项目目录中运行以下命令:
composer require kelvinzer0/curl-impersonate-php
使用方法
以下是一个使用Curl-Impersonate-PHP在模拟浏览器行为的同时发送HTTP请求的示例
require 'vendor/autoload.php'; $curl = new CurlImpersonate\CurlImpersonate(); $curl->setopt(CURLCMDOPT_URL, 'https://example.com/'); $curl->setopt(CURLCMDOPT_METHOD, 'GET'); $curl->setopt(CURLCMDOPT_HEADER, false); $curl->setopt(CURLCMDOPT_ENGINE, "/Users/qindexmedia/Downloads/curl-impersonate-v0.5.4.x86_64-macos/curl_safari15_3"); $response = $curl->execStandard(); echo $response; $curl->closeStream();
请确保将CURLCMDOPT_URL
选项的值替换为适当的目标URL,并根据您的需求设置浏览器模拟。
setopt
函数
setopt
函数用于设置将通过cURL执行的HTTP请求的选项。以下是setopt
函数支持的选项列表
流式使用
除了支持获取HTTP请求执行的普通输出外,Curl-Impersonate-PHP还提供了从正在进行的HTTP请求中流式传输(分块检索数据)响应的能力。您可以使用以下步骤使用流式功能:
- 启用流式传输:在开始HTTP请求之前调用
execStream
函数以启用流式传输
$curl = new CurlImpersonate\CurlImpersonate(); $curl->setopt(CURLCMDOPT_URL, 'https://example.com/'); $curl->setopt(CURLCMDOPT_METHOD, 'GET'); $curl->setopt(CURLCMDOPT_ENGINE, "/Users/qindexmedia/Downloads/curl-impersonate-v0.5.4.x86_64-macos/curl_safari15_3"); $curl->execStream();
- 分块检索数据:您可以使用
readStream
函数以指定大小的块检索响应数据
$chunkSize = 4096; // Size of the data chunks to be retrieved (in bytes) while ($data = $curl->readStream($chunkSize)) { echo $data; // Process the response data here }
- 关闭流式传输:在您完成流式传输的使用后,请确保通过调用
closeStream
函数关闭它
$curl->closeStream();
流式使用示例
以下是在Curl-Impersonate-PHP中使用流式传输的完整示例
$curl = new CurlImpersonate\CurlImpersonate(); $curl->setopt(CURLCMDOPT_URL, 'https://example.com/'); $curl->setopt(CURLCMDOPT_METHOD, 'GET'); $curl->setopt(CURLCMDOPT_ENGINE, "/Users/qindexmedia/Downloads/curl-impersonate-v0.5.4.x86_64-macos/curl_safari15_3"); $curl->execStream(); $chunkSize = 4096; // Size of the data chunks to be retrieved (in bytes) while ($data = $curl->readStream($chunkSize)) { echo $data; // Process the response data here } $curl->closeStream();
请确保将CURLCMDOPT_URL
的值替换为适当的目标URL,并根据您的需求设置浏览器模拟。流式传输特别适用于处理大型响应或需要按顺序分块处理的响应。
贡献
如果您想为Curl-Impersonate-PHP做出贡献,我们非常感谢您的贡献。请在我们GitHub仓库中打开一个新问题或提交一个pull request。
许可协议
Curl-Impersonate-PHP遵循MIT许可协议,这意味着您可以根据许可证条款免费使用、修改和分发此库。