Skip to content

Instantly share code, notes, and snippets.

@gebi84
Created May 18, 2018 13:36
Show Gist options
  • Save gebi84/491182580dcaa1a88411ae229be61c7f to your computer and use it in GitHub Desktop.
Save gebi84/491182580dcaa1a88411ae229be61c7f to your computer and use it in GitHub Desktop.
Guave\Curl -> a simple Curl Class
<?php
namespace Guave\Curl;
class Curl {
const METHOD_POST = 'POST';
const METHOD_GET = 'GET';
const METHOD_PUT = 'PUT';
const METHOD_DELETE = 'DELETE';
/**
* @var null|array $lastRequest;
*/
private static $lastRequest = null;
/**
* @var null|string $lastResponse
*/
private static $lastResponse = null;
/**
* @param string $url
* @param string $method
* @param array $data
* @param array $addHeaders
* @param bool $returnJson
*
* @return array code,response
*/
public static function call($url, $method = 'POST', $data = array(), $addHeaders = array(), $returnJson = false) {
$ch = curl_init();
//api header
$headers = array();
if($addHeaders) {
foreach($addHeaders as $h) {
$headers[] = $h;
}
}
switch($method) {
case self::METHOD_POST:
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
break;
case self::METHOD_GET:
if($data) {
$url = $url.'?'.http_build_query($data);
}
break;
case self::METHOD_PUT:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($data));
break;
case self::METHOD_DELETE:
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
}
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
self::$lastRequest = array(
'url' => $url,
'method' => $method,
'headers' => $headers,
'params' => $data
);
$response = curl_exec ($ch);
self::$lastResponse = $response;
$info = curl_getinfo($ch);
$http_status = $info['http_code'];
curl_close ($ch);
if($returnJson) {
$response = json_decode($response, true);
}
return array('code' => $http_status, 'response' => $response);
}
private function __construct() {
}
private function __clone() {
}
/**
* @return array|null
*/
public static function getLastRequest() {
return self::$lastRequest;
}
/**
* @return null|string
*/
public static function getLastResponse() {
return self::$lastResponse;
}
}
<?php
use Guave\Curl\Curl;
$data = array(
'foo' => 'bar',
);
$call = Curl::call(
'https://example.com',
Curl::METHOD_POST,
$data,
array(),
true
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment