Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Move to Curl instead of file_get_contents
<?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