jsonRPCServer.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. /*
  3. COPYRIGHT
  4. Copyright 2007 Sergio Vaccaro <sergio@inservibile.org>
  5. This file is part of JSON-RPC PHP.
  6. JSON-RPC PHP is free software; you can redistribute it and/or modify
  7. it under the terms of the GNU General Public License as published by
  8. the Free Software Foundation; either version 2 of the License, or
  9. (at your option) any later version.
  10. JSON-RPC PHP is distributed in the hope that it will be useful,
  11. but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. GNU General Public License for more details.
  14. You should have received a copy of the GNU General Public License
  15. along with JSON-RPC PHP; if not, write to the Free Software
  16. Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  17. */
  18. /**
  19. * This class build a json-RPC Server 1.0
  20. * http://json-rpc.org/wiki/specification
  21. *
  22. * @author sergio <jsonrpcphp@inservibile.org>
  23. */
  24. class jsonRPCServer {
  25. /**
  26. * This function handle a request binding it to a given object
  27. *
  28. * @param object $object
  29. * @return boolean
  30. */
  31. public static function handle($object) {
  32. // checks if a JSON-RCP request has been received
  33. if (
  34. $_SERVER['REQUEST_METHOD'] != 'POST' ||
  35. empty($_SERVER['CONTENT_TYPE']) ||
  36. $_SERVER['CONTENT_TYPE'] != 'application/json'
  37. ) {
  38. // This is not a JSON-RPC request
  39. return false;
  40. }
  41. // reads the input data
  42. $request = json_decode(file_get_contents('php://input'),true);
  43. // executes the task on local object
  44. try {
  45. if ($result = @call_user_func_array(array($object,$request['method']),$request['params'])) {
  46. $response = array (
  47. 'id' => $request['id'],
  48. 'result' => $result,
  49. 'error' => NULL
  50. );
  51. } else {
  52. $response = array (
  53. 'id' => $request['id'],
  54. 'result' => NULL,
  55. 'error' => 'unknown method or incorrect parameters'
  56. );
  57. }
  58. } catch (Exception $e) {
  59. $response = array (
  60. 'id' => $request['id'],
  61. 'result' => NULL,
  62. 'error' => $e->getMessage()
  63. );
  64. }
  65. // output the response
  66. if (!empty($request['id'])) { // notifications don't want response
  67. header('content-type: text/javascript');
  68. echo json_encode($response);
  69. }
  70. // finish
  71. return true;
  72. }
  73. }
  74. ?>