Skip to content

Instantly share code, notes, and snippets.

@zjhiphop
Forked from jasdeepkhalsa/RestServer.php
Created August 30, 2017 06:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zjhiphop/f7777b1b1b312c79d025b8d4cabd8e66 to your computer and use it in GitHub Desktop.
Save zjhiphop/f7777b1b1b312c79d025b8d4cabd8e66 to your computer and use it in GitHub Desktop.
Simple PHP REST / JSON Server with example.php by Jake Sankey (http://jakesankey.com/blog/2012/09/php-simple-rest-server/)
<?php
// example request: http://path/to/resource/Example?method=sayHello&name=World
require_once "RestServer.php";
$rest = new RestServer(Hello);
$rest->handle();
class Hello
{
public static function sayHello($name)
{
return "Hello, " . $name;
}
}
?>
<?php
class RestServer
{
public $serviceClass;
public function __construct($serviceClass)
{
$this->serviceClass = $serviceClass;
}
public function handle()
{
if (array_key_exists("method", array_change_key_case($_REQUEST, CASE_LOWER)))
{
$rArray = array_change_key_case($_REQUEST, CASE_LOWER);
$method = $rArray["method"];
if (method_exists($this->serviceClass, $method))
{
$ref = new ReflectionMethod($this->serviceClass, $method);
$params = $ref->getParameters();
$pCount = count($params);
$pArray = array();
$paramStr = "";
$i = 0;
foreach ($params as $param)
{
$pArray[strtolower($param->getName())] = null;
$paramStr .= $param->getName();
if ($i != $pCount-1)
{
$paramStr .= ", ";
}
$i++;
}
foreach ($pArray as $key => $val)
{
$pArray[strtolower($key)] = $rArray[strtolower($key)];
}
if (count($pArray) == $pCount && !in_array(null, $pArray))
{
echo call_user_func_array(array($this->serviceClass, $method), $pArray);
}
else
{
echo json_encode(array('error' => "Required parameter(s) for ". $method .": ". $paramStr));
}
}
else
{
echo json_encode(array('error' => "The method " . $method . " does not exist."));
}
}
else
{
echo json_encode(array('error' => 'No method was requested.'));
}
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment