Skip to content

Instantly share code, notes, and snippets.

@edwardgalligan
Last active February 10, 2017 13:29
Show Gist options
  • Save edwardgalligan/c394e28cc302aee6f8ae44e550613a34 to your computer and use it in GitHub Desktop.
Save edwardgalligan/c394e28cc302aee6f8ae44e550613a34 to your computer and use it in GitHub Desktop.
Simple as chips wrapper around PHP curl
<?php
/**
* Simple as chips wrapper around PHP curl
* @author git@lucideer.com
*/
namespace lucideer;
use Composer\CaBundle\CaBundle;
class CURL
{
/**
* Simple wrapper around a cURL HTTP request
* Should support most common request types
* Should "just work" for HTTP/HTTPS (*_SSL_* options are ignored for HTTP)
*
* @depends https://packagist.org/packages/composer/ca-bundle
* @param $method string - HTTP method
* @param $url string - URL for the request
* @param $body string optional - request body as a plain string
* @param $headers array optional - key value hash of HTTP headers
* @return $responseData \StdClass - object of the following form:
* {
* request : original request (for debugging)
* response: <cURL response body string>,
* info : <cURL info array>,
* error : <cURL error string>,
* };
*/
public function httpRequest($method, $url, $body = '', $headers = [])
{
if ($body !== '') {
$headers['Content-Length'] = mb_strlen($body, 'UTF-8');
}
$caBundlePath = CaBundle::getSystemCaRootBundlePath();
$c = curl_init();
curl_setopt_array($c, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_URL => $url,
CURLOPT_POSTFIELDS => $body,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_CAINFO => $caBundlePath,
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_SSL_VERIFYPEER => true
]);
$request = $this->prettyPrintRequest($method, $url, $headers, $body);
$response = curl_exec($c);
$info = curl_getinfo($c);
$error = curl_error($c);
curl_close($c);
return (object) [
'request' => $request,
'response' => $response,
'info' => $info,
'error' => $error
];
}
/**
* Quick little utility method for pretty-printing the request for debug
*
* @param $method string - HTTP method
* @param $url string - full URL
* @param $headers array - headers as fed to CURLOPT_HTTPHEADER
* @param $body string optiona - POST body, if any
* @return string - the formatted request
*/
private function prettyPrintRequest($method, $url, $headers, $body='')
{
$path = preg_replace('/^([a-z]*:)?\/\/\/?[a-z:@]*[^\/]*/i', '', $url);
$allHeaders = $headers + ['Host' => parse_url($url, PHP_URL_HOST)];
$headerString = implode("\n", array_map(
function ($k, $v) { return "$k: $v"; },
array_keys($allHeaders),
$allHeaders
));
return "$method $path HTTP/1.1\n$headerString\n\n$body";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment