Last active
May 22, 2018 18:29
-
-
Save scottchiefbaker/43a479178f6850e70ea0 to your computer and use it in GitHub Desktop.
Move to Curl instead of file_get_contents
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Create the client object | |
// $url = "https://scott.internal.web-ster.com/api/json-rpc/"; | |
// $j = new jsonrpc_client($url); | |
// Run the echo_data() function | |
// $a = $j->echo_data('one','two'); | |
// if $a === null, there was some sort of error | |
// Examine: $j->last for raw error information | |
////////////////////////////////////////////////////////////////////////////////// | |
// Baker JSON-RPC client version 0.2 | |
class jsonrpc_client { | |
function __construct($url) { | |
if (!preg_match("/^http/i",$url)) { | |
return false; | |
} | |
$this->url = $url; | |
$this->breadcrumb = array(); | |
$this->last = array(); | |
} | |
function __get($name) { | |
$this->breadcrumb[] = $name; | |
return $this; | |
} | |
function __call($method,$args) { | |
if (isset($this->breadcrumb) && sizeof($this->breadcrumb) > 0) { | |
$method = join(".",$this->breadcrumb) . "." . $method; | |
} | |
$data = array('method' => $method, 'params' => $args, 'jsonrpc' => '2.0', 'id' => 1); | |
$json = json_encode($data); | |
$ch = curl_init(); | |
curl_setopt($ch, CURLOPT_URL, $this->url); | |
curl_setopt($ch, CURLOPT_POST, true); // Post not get | |
curl_setopt($ch, CURLOPT_POSTFIELDS, $json); // Raw JSON for POST | |
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (X11; Linux x86_64; rv:1.0) Baker/PHP-JSON-RPC 0.2'); | |
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return the string instead of printing it out | |
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Don't check SSL certs | |
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2); // Timeout to connect | |
curl_setopt($ch, CURLOPT_TIMEOUT, 5); // Timeout waiting for a response | |
$resp = curl_exec($ch); | |
$resp_info = curl_getinfo($ch); | |
$http_code = $resp_info['http_code']; | |
$this->breadcrumb = array(); | |
$ret = json_decode($resp,true); | |
// The JSON parsed corrected | |
if ($ret != null) { | |
$this->last = $ret; | |
// Invalid JSON | |
} else { | |
$this->last = array( | |
"protocol_error" => true, | |
"http_code" => $http_code, | |
"error" => [ | |
"message" => $resp, | |
'error_number' => 8360 | |
] | |
); | |
} | |
if (empty($ret['result'])) { | |
$ret = null; | |
} else { | |
$ret = $ret['result']; | |
} | |
return $ret; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment