1 <?php
2 class jsonRPC {
4 private $curlHandler = NULL;
5 private $debug;
6 private $url;
7 private $id;
9 public function __construct($url,$debug = false)
10 {
12 $this->url = $url;
13 $this->debug = $debug;
14 $this->id = 0;
16 // Init Curl handler
17 $this->curlHandler = curl_init($this->url);
18 curl_setopt($this->curlHandler, CURLOPT_URL , $this->url);
19 curl_setopt($this->curlHandler, CURLOPT_COOKIESESSION , TRUE);
20 curl_setopt($this->curlHandler, CURLOPT_COOKIEFILE, 'cookiefile.txt');
21 curl_setopt($this->curlHandler, CURLOPT_POST , TRUE);
22 curl_setopt($this->curlHandler, CURLOPT_RETURNTRANSFER , TRUE);
23 curl_setopt($this->curlHandler, CURLOPT_HTTPHEADER , array('Content-Type: application/json'));
24 }
26 public function get_error()
27 {
28 return(curl_error($this->curlHandler));
29 }
31 public function success()
32 {
33 return(curl_errno($this->curlHandler) == 0);
34 }
36 public function __destruct()
37 {
38 curl_close($this->curlHandler);
39 }
41 public function __call($method,$params)
42 {
43 if (!is_scalar($method)) trigger_error('jsonRPC::__call requires a scalar value as first parameter!');
45 if (is_array($params)) {
46 $params = array_values($params);
47 } else {
48 trigger_error('jsonRPC::__call requires an array value as second parameter!');
49 }
51 // prepares the request
52 $this->id ++;
53 $request = json_encode(array('method' => $method,'params' => $params,'id' => $this->id));
55 // Set curl options
56 curl_setopt($this->curlHandler, CURLOPT_POSTFIELDS , $request);
57 $response = curl_exec($this->curlHandler);
58 $response = json_decode($response,true);
60 // Check responce id
61 if ($response['id'] != $this->id){
62 #trigger_error('jsonPRC returned incorrect response '.
63 # 'id (request id: '.$this->id.', response id: '.$response['id'].')');
64 }
65 return($response['result']);
66 }
67 }
68 ?>