Skip to content

Instantly share code, notes, and snippets.

@glagola
Last active August 29, 2015 14:01
Show Gist options
  • Save glagola/940625457171969b08f8 to your computer and use it in GitHub Desktop.
Save glagola/940625457171969b08f8 to your computer and use it in GitHub Desktop.
<?php
class HttpError extends Exception { }
class Curl {
private $ch;
private $headers;
protected function baseSettings() {
return [
/* Flags */
CURLOPT_HEADER => false,
CURLOPT_AUTOREFERER => false,
CURLOPT_FORBID_REUSE => false,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_RETURNTRANSFER => true,
/* Strings */
CURLOPT_ENCODING => '',
CURLOPT_USERAGENT => 'Mozilla/5.0 (X11; Linux x86_64; rv:29.0) Gecko/20100101 Firefox/27.0',
/* Integers */
CURLOPT_TIMEOUT => 10,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CONNECTTIMEOUT => 5,
];
}
protected function applyBaseSettings() {
$this->headers['DNT'] = 1;
curl_setopt_array($this->ch, $this->baseSettings());
}
public static function create() {
return new self;
}
public function __construct() {
$this->ch = curl_init();
self::applyBaseSettings($this->ch);
}
public function __destruct() {
curl_close($this->ch);
}
public function setUrl($url) {
curl_setopt($this->ch, CURLOPT_URL, $url);
return $this;
}
public function setMethod($method) {
$method = strtoupper(trim($method));
curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, $method);
return $this;
}
public function setBody($body) {
curl_setopt($this->ch, CURLOPT_POSTFIELDS, $body);
$this->setHeader('Content-Length', (string)strlen($body));
return $this;
}
public function setHeader($header, $value) {
$this->headers[$header] = $value;
return $this;
}
public function setHeaders(array $headers) {
foreach((array)$headers as $header => $value) {
$this->setHeader($header, $value);
}
return $this;
}
public function setReferer($referrer) {
curl_setopt($this->ch, CURLOPT_REFERER, $referrer);
return $this;
}
public function viaProxy($host, $port, $user = NULL, $password = NULL) {
curl_setopt($this->ch, CURLOPT_PROXY, "$host:$port");
if (!empty($user) && !empty($password)) {
curl_setopt($this->ch, CURLOPT_PROXYUSERPWD, "$user:$password");
}
return $this;
}
protected function convHeaders($headers) {
$result = [];
foreach((array)$headers as $header => $value) {
$result []= "$header: $value";
}
return $result;
}
public function exec() {
$headers = $this->convHeaders($this->headers);
curl_setopt($this->ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($this->ch);
if ($response === false) {
$code = curl_getinfo($this->ch, CURLINFO_HTTP_CODE);
throw new HttpError("Http request failure", $code);
}
return $response;
}
public function get($url = NULL) {
$this->setMethod("GET");
return $this->exec();
}
public function post() {
$this->setMethod("POST");
return $this->exec();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment