Skip to content

Instantly share code, notes, and snippets.

@nicklasos
Last active April 19, 2016 11:05
Show Gist options
  • Save nicklasos/11045031 to your computer and use it in GitHub Desktop.
Save nicklasos/11045031 to your computer and use it in GitHub Desktop.
Curl
<?php
namespace App\Utils;
/**
* Simple curl wrapper
* @package Plariumed\Utils
*
* $curl = new Curl('http://localhost/api');
* $curl
* ->set(CURLOPT_USERPWD, 'appKey:appSecret')
* ->set(CURLOPT_POST, true)
* ->set(CURLOPT_POSTFIELDS, json_encode(['data' => 'test']))
* ->set(CURLOPT_HEADER, false)
* ->set(CURLOPT_RETURNTRANSFER, true)
* ->set(CURLOPT_HTTPHEADER, [
* 'Content-Type:application/json',
* 'Accept: application/vnd.urbanairship+json; version=3;'
* ]);
*
* $response = $curl->exec();
* $info = $curl->info();
*
* $response = $info['http_code'] === 200 ? json_decode($response) : $response;
* $curl->close();
*/
class Curl
{
/**
* @var resource
*/
private $curl;
/**
* @param string $url
*/
public function __construct($url = null)
{
$this->init($url);
}
/**
* @param null|string $url
*/
public function init($url = null)
{
if ($url) {
$this->curl = curl_init($url);
}
}
/**
* @param int $param
* @param mixed $value
* @return $this
*/
public function set($param, $value)
{
curl_setopt($this->curl, $param, $value);
return $this;
}
/**
* @param array $params
* @return $this
*/
public function setParams(array $params)
{
foreach ($params as $param => $value) {
$this->set($param, $value);
}
return $this;
}
/**
* @return array
*/
public function exec()
{
return curl_exec($this->curl);
}
/**
* @return array
*/
public function info()
{
return curl_getinfo($this->curl);
}
/**
* @return string
*/
public function error()
{
return curl_error($this->curl);
}
/**
*
*/
public function close()
{
curl_close($this->curl);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment