powderblue / curl
PHP 的基本 CURL 包装器。这是 @shuber 的简单、优秀的 cURL 包装器的现代化版本,https://github.com/shuber/curl。
Requires
- php: >=7.4.27
- ext-curl: *
Requires (Dev)
- danbettles/codesniffer-standard: ^2.0
- jaz303/ztest: ^0.0.3
- phpstan/phpstan: ^1.10
- squizlabs/php_codesniffer: ^3.7
README
PHP 的基本 cURL 包装器。
ℹ️ 更多关于 PHP cURL 扩展的信息,请参阅 https://php.ac.cn/curl
此分支是 @shuber 的简单、优秀的 cURL 包装器 的现代化版本。
安装
使用 Composer。
使用方法
初始化
简单要求并初始化 Curl
类,如下所示
require '<your-project-dir>/vendor/autoload.php'; $curl = new PowderBlue\Curl\Curl();
执行请求
Curl
类提供了使用 HEAD
、GET
、POST
、PUT
和 DELETE
方法进行请求的快捷方式。您必须始终指定一个 URL;如果需要,您还可以传递一个数组/字符串的变量,与 URL 一起发送。
// When making `HEAD` and `GET` requests, parameters will be appended to the URL in the form of a query-string $response = $curl->head($url, $requestParams); $response = $curl->get($url, $requestParams); // Otherwise, you can pass an associative array or a string to pop into the body of the request $response = $curl->post($url, $requestBody); $response = $curl->put($url, $requestBody); $response = $curl->delete($url, $requestBody);
使用 Curl::request()
使用自定义请求方法进行请求,如下所示
$response = $curl->request('<method-name>', $url, $requestBody);
示例
$response = $curl->get('https://www.google.com/?q=test'); // In this case, '?q=test' will be appended to the URL $response = $curl->get('https://www.google.com/', ['q' => 'test']); // The data will be encoded for you and the `Content-Type` header set to `multipart/form-data` $response = $curl->post('test.com/posts', ['title' => 'Test', 'body' => 'This is a test']);
如果成功,所有请求都返回 PowderBlue\Curl\Response
实例,如果发生错误,则抛出异常。
响应类
正常的 cURL 请求将头和体作为一个单一字符串返回。PowderBlue\Curl\Response
类将此字符串拆分,将两部分放入单独的属性中。
例如
$response = $curl->get('https://www.google.com/'); echo $response->body; print_r($response->headers);
将显示类似的内容
<html> <head> <title>Google.com</title> </head> <body> ... </body> </html> Array ( [Http-Version] => 1.0 [Status-Code] => 200 [Status] => 200 OK [Cache-Control] => private [Content-Type] => text/html; charset=ISO-8859-1 [Date] => Wed, 07 May 2008 21:43:48 GMT [Server] => gws [Connection] => close )
ℹ️
PowderBlue\Curl\Response::__toString()
返回响应体,因此——例如——echo $response
将与echo $response->body
输出相同。
Cookie/会话
默认情况下,cookie 将存储在 <lib-dir>/var/curl_cookie.txt
。您可以通过以下方式更改此设置。
$curl->cookie_file = '<pathname>';
这允许您在请求之间保持会话。
基本配置选项
您可以轻松设置引用或用户代理
$curl->referer = '<url>'; $curl->user_agent = '<user-agent-string>';
设置头部
您可以指定与请求一起发送的头部
$curl->headers['Host'] = 12.345.678.90; $curl->headers['Custom-Header'] = 'foo'; $curl->headers['User-Agent'] = '<user-agent-string>';
设置自定义 cURL 请求选项
默认情况下,将跟随重定向。您可以通过以下方式禁用此功能
$curl->follow_redirects = false;
如果您需要进行一些更复杂的事情,您可以像这样设置/覆盖 cURL 选项
$curl->options[CURLOPT_AUTOREFERER] = true;
ℹ️ 请参阅
curl_setopt()
文档 了解 cURL 请求选项列表
联系我
问题、评论和建议都欢迎: support@powder-blue.com。