alkurn / yii2-curl
为 Yii2 提供简单且美观的 cURL 扩展,支持 RESTful
dev-master
2017-06-13 07:02 UTC
Requires
- ext-curl: *
- yiisoft/yii2: *
Requires (Dev)
- codeception/base: ^2.2.3
- codeception/specify: ~0.4.3
- codeception/verify: ~0.3.1
- codeclimate/php-test-reporter: dev-master
- guzzlehttp/guzzle: >=4.1.4 <7.0
- mcustiel/phiremock-codeception-extension: 1.2.4
This package is not auto-updated.
Last update: 2024-09-20 19:37:50 UTC
README
为 Yii2 提供简单的 cURL 扩展,包括 RESTful 支持
- POST
- GET
- HEAD
- PUT
- PATCH
- DELETE
要求
- Yii2
- PHP 5.4+
- Curl 和 php-curl 已安装
安装
安装此扩展的首选方式是通过 composer。
php composer.phar require --prefer-dist alkurn/yii2-curl "dev-master"
composer require --prefer-dist alkurn/yii2-curl "dev-master"
使用方法
安装扩展后,只需在代码中使用它。以下示例展示了如何处理简单的 GET 请求。
use alkurn\curl; $curl = new curl\Curl(); //get http://example.com/ $response = $curl->get('http://example.com/'); if ($curl->errorCode === null) { echo $response; } else { // List of curl error codes here https://curl.haxx.se/libcurl/c/libcurl-errors.html switch ($curl->errorCode) { case 6: //host unknown example break; } }
// GET request with GET params // http://example.com/?key=value&scondKey=secondValue $curl = new curl\Curl(); $response = $curl->setGetParams([ 'key' => 'value', 'secondKey' => 'secondValue' ]) ->get('http://example.com/');
// POST URL form-urlencoded $curl = new curl\Curl(); $response = $curl->setPostParams([ 'key' => 'value', 'secondKey' => 'secondValue' ]) ->post('http://example.com/');
// POST with special headers $curl = new curl\Curl(); $response = $curl->setPostParams([ 'key' => 'value', 'secondKey' => 'secondValue' ]) ->setHeaders([ 'Custom-Header' => 'user-b' ]) ->post('http://example.com/');
// POST JSON with body string & special headers $curl = new curl\Curl(); $params = [ 'key' => 'value', 'secondKey' => 'secondValue' ]; $response = $curl->setRequestBody(json_encode($params)) ->setHeaders([ 'Content-Type' => 'application/json', 'Content-Length' => strlen(json_encode($params)) ]) ->post('http://example.com/');
// Avanced POST request with curl options & error handling $curl = new curl\Curl(); $params = [ 'key' => 'value', 'secondKey' => 'secondValue' ]; $response = $curl->setRequestBody(json_encode($params)) ->setOption(CURLOPT_ENCODING, 'gzip') ->post('http://example.com/'); // List of status codes here http://en.wikipedia.org/wiki/List_of_HTTP_status_codes switch ($curl->responseCode) { case 'timeout': //timeout error logic here break; case 200: //success logic here break; case 404: //404 Error logic here break; } //list response headers var_dump($curl->responseHeaders);