Skip to content

Instantly share code, notes, and snippets.

@hubgit
Created May 20, 2012 14:49
Show Gist options
  • Save hubgit/2758365 to your computer and use it in GitHub Desktop.
Save hubgit/2758365 to your computer and use it in GitHub Desktop.
PHP HTTP Client
<?php
class HTTP {
function curl_init($url) {
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_VERBOSE, DEBUG);
return $curl;
}
function curl_exec($curl) {
$data = curl_exec($curl);
switch ($this->detect_content_type($curl)) {
case 'application/json':
return json_decode($data, true);
default:
return $data;
}
}
function detect_content_type($curl) {
$parts = explode(';', curl_getinfo($curl, CURLINFO_CONTENT_TYPE));
return trim($parts[0]);
}
function http_build_url($url, $params) {
if ($params) $url .= '?' . http_build_query($params);
return $url;
}
function get($url, $params = array(), $headers = array()) {
$url = $this->http_build_url($url, $params);
$curl = $this->curl_init($url);
if ($headers) curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
return $this->curl_exec($curl);
}
function post($url, $params, $headers = array()) {
$curl = $this->curl_init($url);
curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
if ($headers) curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
return $this->curl_exec($curl);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment