Skip to content

Instantly share code, notes, and snippets.

@wilon
Last active November 7, 2017 06:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wilon/9f50937ef4cdc91de9f1253340238b63 to your computer and use it in GitHub Desktop.
Save wilon/9f50937ef4cdc91de9f1253340238b63 to your computer and use it in GitHub Desktop.
<?php
/**
* simple curl
* @param string $url
* @param array $param
* @return mix
*/
function simpleCurl($url = '', $param = []) {
// params init
if (!$url) return false;
$parseUrl = parse_url($url);
if (!isset($param['method'])) $param['method'] = 'get';
$param['method'] = strtoupper($param['method']);
if (!isset($param['data'])) $param['data'] = [];
if (!isset($param['header'])) $param['header'] = [];
if (!isset($param['cookie'])) $param['cookie'] = [];
if (!isset($param['return'])) $param['return'] = 'body';
// cookie keep
$sessionKey = md5($parseUrl['host'] . 'simple-curl');
$cookieFunc = function ($action = 'get', $cookieData = []) use ($sessionKey) {
$dir = __DIR__ . '/simple-curl-cache';
@mkdir($dir);
if ($action == 'set') {
return @file_put_contents("$dir/$sessionKey", json_encode($cookieData));
} else {
return json_decode(@file_get_contents("$dir/$sessionKey"), true);
}
};
// curl init
$ch = curl_init();
if ($param['method'] == 'get' && $param['data']) {
$joint = $parseUrl['query'] ? '&' : '?';
$url .= $joint . http_build_query($param['data']);
}
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
// https支持
if ($parseUrl['scheme'] == 'https') {
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
}
// header
$header = [];
if (strpos(json_encode($param['header']), 'User-Agent') === false) {
$header[] = 'User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36';
}
if (is_string($param['header'])) {
foreach (explode("\n", $param['header']) as $v) {
$header[] = trim($v);
}
} else if (is_array($param['header'])) {
$header = array_merge($header, $param['header']);
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
// cookie keep
$curloptCookie = '';
$cookieData = $cookieFunc('get');
if (is_string($param['cookie'])) {
$curloptCookie .= $param['cookie'];
} else if (is_array($param['cookie']) && is_array($cookieData)) {
$cookieData = array_merge($cookieData, $param['cookie']);
}
if ($cookieData) {
foreach ($cookieData as $k => $v) {
$curloptCookie .= "$k=$v;";
}
}
curl_setopt($ch, CURLOPT_COOKIE, $curloptCookie);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
// method
switch ($param['method']){
case "GET" :
curl_setopt($ch, CURLOPT_HTTPGET, true);
break;
case "POST":
curl_setopt($ch, CURLOPT_POST,true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $param['data']);
break;
case "PUT" :
curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, $param['data']);
break;
case "PATCH":
curl_setopt($ch, CULROPT_CUSTOMREQUEST, 'PATCH');
curl_setopt($ch, CURLOPT_POSTFIELDS, $param['data']);
break;
case "DELETE":
curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_POSTFIELDS, $param['data']);
break;
}
// response
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = trim(substr($response, 0, $headerSize));
$body = trim(substr($response, $headerSize));
curl_close($ch);
// update cookie
preg_match_all('/Set-Cookie:(.*?)\n/', $header, $matchesCookie);
if (is_array($matchesCookie[1])) {
foreach ($matchesCookie[1] as $setCookie) {
foreach (explode(';', $setCookie) as $cookieStr) {
@list($key, $value) = explode('=', trim($cookieStr));
$cookieData[$key] = $value;
}
}
}
$cookieFunc('set', $cookieData);
// return
$return = $param['return'] == 'header' ? $header :
($param['return'] == 'all' ? [$header, $body] : $body);
return $return;
}
@wilon
Copy link
Author

wilon commented Nov 6, 2017

How to use?

<?php

// simple request
$res[] = simpleCurl('http://github.com/wilon');


// get request: http://github.com/wilon?username=wilon&password=test
$res[] = simpleCurl('http://github.com/wilon', [
    'data' => [
        'username' => 'wilon',
        'password' => 'test',
    ]]
);


// return what
$res[] = simpleCurl('https://api.github.com/', [
    'return' => 'header'
]);


// set header
$res[] = simpleCurl('https://api.github.com/', [
    'header' => [
        'GET /v4/guides/intro-to-graphql/ HTTP/1.1',
        'Host: developer.github.com'
    ],
]);
// Or you can copy from chrome-dev-tool [ Response Headers  view source ]
$res[] = simpleCurl('https://api.github.com/', [
    'header' => 'GET /v4/guides/intro-to-graphql/ HTTP/1.1
Host: developer.github.com
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Referer: https://developer.github.com/
Accept-Encoding: gzip, deflate, br
Accept-Language: en,zh-CN;q=0.8,zh;q=0.6,zh-TW;q=0.4,mt;q=0.2,fr;q=0.2,pt;q=0.2,ja;q=0.2,da;q=0.2,pl;q=0.2,lt;q=0.2',
]);


// post or other..
$res[] = simpleCurl('https://api.github.com/events', [
    'method' => 'post',
    'data' => [
        'username' => 'wilon',
        'password' => 'test',
    ]
]);


die(var_dump($res));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment