Skip to content

Instantly share code, notes, and snippets.

@therealklanni
Created August 23, 2012 18:45
Show Gist options
  • Save therealklanni/3440166 to your computer and use it in GitHub Desktop.
Save therealklanni/3440166 to your computer and use it in GitHub Desktop.
RESTRequest is a PHP class for handling cURL requests, specifically for use with RESTful web services. Supports session states.
<?php
class RESTRequest
{
public $response;
public $code;
private $handle;
private $session;
private $curlopts;
public function __construct()
{
$this->handle = curl_init();
$cookiejar = tempnam(sys_get_temp_dir(), 'session');
$headers = array(
'Accept: application/json',
'Content-Type: application/json',
);
$this->curlopts = array(
CURLOPT_HTTPHEADER=>$headers,
CURLINFO_HEADER_OUT=>true,
CURLOPT_RETURNTRANSFER=>true,
CURLOPT_COOKIEJAR=>$cookiejar,
CURLOPT_COOKIEFILE=>$cookiejar,
CURLOPT_SSL_VERIFYHOST=>false,
CURLOPT_SSL_VERIFYPEER=>false,
);
}
/**
* @return (object) cURL handle
*/
public function getHandle()
{
return $this->handle;
}
/**
* @param (array) $headers Array of header values
* @return (array) Headers
*/
public function setHeaders($headers)
{
$this->curlopts[CURLOPT_HTTPHEADER] = $headers;
curl_setopt_array($this->handle, $this->curlopts);
$this->getHeaders();
}
/**
* @return (array) Headers
*/
public function getHeaders()
{
return $this->curlopts[CURLOPT_HTTPHEADER];
}
/**
* @param (string) $method GET/PUT/POST/DELETE
* @param (string) $url Request URL
* @param (json) $data JSON data (optional)
* @return (boolean) TRUE
*/
public function setUp($method, $url, $data='')
{
curl_setopt_array($this->handle, $this->curlopts);
curl_setopt($this->handle, CURLOPT_URL, $url);
if ($this->session)
curl_setopt($this->handle, CURLOPT_COOKIE, $this->session);
switch(strtoupper($method)) {
case 'GET':
break;
case 'POST':
curl_setopt($this->handle, CURLOPT_POST, true);
curl_setopt($this->handle, CURLOPT_POSTFIELDS, $data);
break;
case 'PUT':
curl_setopt($this->handle, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($this->handle, CURLOPT_POSTFIELDS, $data);
break;
case 'DELETE':
curl_setopt($this->handle, CURLOPT_CUSTOMREQUEST, 'DELETE');
break;
}
return true;
}
/**
* @return (boolean) Success of HTTP request
*/
public function send()
{
$this->response = curl_exec($this->handle);
$this->code = curl_getinfo($this->handle, CURLINFO_HTTP_CODE);
if (!$this->session)
$this->session = session_id() .'='. session_id() .'; path=' . session_save_path();
session_write_close();
return !!$this->response;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment