PHP code example of gaoming13 / http-curl
1. Go to this page and download the library: Download gaoming13/http-curl library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
gaoming13 / http-curl example snippets
use Gaoming13\HttpCurl\HttpCurl;
// 普通GET
// curl 'http://example.com/'
$res = HttpCurl::request('http://example.com/', 'get');
// GET带参数
// curl 'http://example.com/?a=123&b=456'
$res = HttpCurl::request('http://example.com/?a=123', 'get', array(
'b' => '456'
));
// POST Form-Data(Form Data)
// curl 'http://example.com/?ac=login' \
// --data-raw 'username=root&password=123456'
$res = HttpCurl::request('http://example.com/?ac=login', 'post', array(
'username' => 'root',
'password' => '123456'
));
// POST RAW(Request Payload)
// curl 'http://example.com/?ac=login' \
// --data-binary '{"username":"root","password":"123456"}'
$res = HttpCurl::request('http://example.com/?ac=login', 'post', '{"username":"root","password":"123456"}', [
'Content-Type:application/json'
]);
// POST 上传图片
$res = HttpCurl::request('http://example.com/', 'post', array(
'file1' => '@/data/sky.jpg',
'file2' => '@/data/bird.jpg'
), [
'Content-Type: image/jpeg'
]);
$res = HttpCurl::request('http://example.com/', 'post', array(
'file1' => '@G:\wamp\www\data\sky.jpg',
'file2' => '@G:\wamp\www\data\bird.jpg'
));
list($body, $header, $status, $errno, $error) =
HttpCurl::request(
// 请求地址
'http://example.com/',
// 请求方式(post/get)
'get',
// 传递的参数(get为queryString, post为Request Payload)
array(
'username' => 'root',
'password' => '123456'
),
// 请求头(cookie写在这里)
[
'Accept: text/plain, */*; q=0.01',
'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36',
'Referer: https://www.baidu.com/',
'Cookie: BD_UPN=123253; PSTM=1592901563;'
],
// 超时时间(秒)
5
);
// 响应正文(string)(获取失败返回空字符串)
var_dump($body);
// 响应头(string)(原始格式)
var_dump($header);
// 响应状态(array)(数组)
var_dump($status);
// 错误码(int)(0表示正常响应)
// 其它错误码见:https://www.php.net/manual/zh/function.curl-errno.php
var_dump($errno);
// GET请求
HttpCurl::get('http://api.example.com/');
// GET请求, 并json_decode返回的数组
HttpCurl::get('http://api.example.com/?a=123&b=456', 'json');
// POST请求
HttpCurl::post('http://api.example.com/?a=123', array(
'abc'=>'123',
'efg'=>'567'
));
HttpCurl::post('http://api.example.com/', '这是post原始内容', 'json');
// POST请求, 文件上传
HttpCurl::post('http://api.example.com/', array(
'file1'=>'@/data/sky.jpg',
'file2'=>'@/data/bird.jpg',
));