Skip to content

Instantly share code, notes, and snippets.

@Zenger
Last active December 20, 2015 22:59
Show Gist options
  • Save Zenger/6209001 to your computer and use it in GitHub Desktop.
Save Zenger/6209001 to your computer and use it in GitHub Desktop.
A simple request class, makes use of CURL.
<?php
class Request {
public $curl_object;
public function __construct($p_username = "", $p_password = "", $p_timeout = 15)
{
$this->curl_object = curl_init();
curl_setopt($this->curl_object, CURLOPT_HTTPHEADER, Array("Accept: application/json", "Content-Type: application/json"));
curl_setopt($this->curl_object, CURLOPT_CONNECTTIMEOUT, $p_timeout);
curl_setopt($this->curl_object, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($this->curl_object, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($this->curl_object, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:22.0) Gecko/20100101 Firefox/22.0");
if(!empty($p_username) && !empty($p_password)) {
curl_setopt($this->curl_object, CURLOPT_USERPWD, $p_username . ":" . $p_password);
curl_setopt($this->curl_object, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
}
}
public function get_request($p_url)
{
curl_setopt($this->curl_object, CURLOPT_URL, $p_url);
return curl_exec($this->curl_object);
}
public function post_request($p_url, $p_post_data = "")
{
curl_setopt($this->curl_object, CURLOPT_URL, $p_url);
curl_setopt($this->curl_object, CURLOPT_POST, true);
curl_setopt($this->curl_object, CURLOPT_POSTFIELDS, $p_post_data);
return curl_exec($this->curl_object);
}
public function put_request($p_url)
{
curl_setopt($this->curl_object, CURLOPT_URL, $p_url);
curl_setopt($this->curl_object, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($this->curl_object, CURLOPT_POSTFIELDS, "");
return curl_exec($this->curl_object);
}
public function delete_request($p_url)
{
curl_setopt($this->curl_object, CURLOPT_URL, $p_url);
curl_setopt($this->curl_object, CURLOPT_CUSTOMREQUEST, 'DELETE');
return curl_exec($this->curl_object);
}
public function close()
{
curl_close($this->curl_object);
}
public function download($link , $filename = "file.tmp")
{
$fp = fopen ($filename, 'w+');//This is the file where we save the information
curl_setopt($this->curl_object, CURLOPT_URL, $link);
curl_setopt($this->curl_object, CURLOPT_FILE, $fp); // write curl response to file
curl_setopt($this->curl_object, CURLOPT_FOLLOWLOCATION, true);
$ret = curl_exec($this->curl_object);
fclose($fp);
return $ret;
}
public function chunk_download($file_source, $file_target, $chunk = 4096)
{
$rh = fopen($file_source, 'rb');
$wh = fopen($file_target, 'w+b');
if (!$rh || !$wh)
{
return false;
}
while (!feof($rh))
{
if (fwrite($wh, fread($rh, $chunk)) === FALSE) {
return false;
}
echo ' ';
flush();
}
fclose($rh);
fclose($wh);
return true;
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment