Skip to content

Instantly share code, notes, and snippets.

@anushshukla
Created June 6, 2019 06:38
Show Gist options
  • Select an option

  • Save anushshukla/a39f2482bd886ea9d6a543ca082e44e8 to your computer and use it in GitHub Desktop.

Select an option

Save anushshukla/a39f2482bd886ea9d6a543ca082e44e8 to your computer and use it in GitHub Desktop.
PHP file to abstracting and encapsulation of making curl calls following OOPS
<?php
class Curl {
private $_ch;
protected $opts;
private function __construct($config)
{
$this->_ch = curl_init();
}
public static function init()
{
if(!function_exists('curl_version')
|| !in_array('curl', get_loaded_extensions())
|| !extension_loaded('curl')
) :
throw new Exception("Please install / enable Curl on your server",400);
endif;
return new Curl(func_get_args());
}
public function send($url, $method = "GET", $data = array())
{
$opts["url"] = $this->url;
$opts["method"] = $this->method;
$opts["data"] = $this->data;
$this->opts = array_replace_recursive($this->opts, $opts);
curl_setopt_array($this->_ch, $this->opts);
$resp = curl_exec($this->_ch);
if($resp === FALSE) :
if(ini_get('display_errors')) :
throw new Exception('Curl Error: ' . curl_error($this->_ch),417);
else :
error_log('Curl Error: ' . curl_error($this->_ch));
endif;
endif;
// $curl->getResponseHeader();
// $curl->getResponseBody();
return $resp;
}
private function __destruct()
{
curl_close($this->_ch);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment