diff --git a/README.md b/README.md index 0f3f49e..e3d3253 100644 --- a/README.md +++ b/README.md @@ -243,6 +243,10 @@ class Tools { ``` +### Way 4. Automatic detect receive `Content-Type` as `application/json`, parse `php://input` + +All data will be writed into `$_POST` + ## Responses The response body is always a array (JSON per default) containing a status code and the actual data. diff --git a/RestService/Server.php b/RestService/Server.php index da90476..73ed037 100644 --- a/RestService/Server.php +++ b/RestService/Server.php @@ -139,6 +139,7 @@ class Server public function __construct($pTriggerUrl, $pControllerClass = null, $pParentController = null) { $this->normalizeUrl($pTriggerUrl); + $this->detectContentType(); if ($pParentController) { $this->parentController = $pParentController; @@ -1205,4 +1206,26 @@ public function findRoute($pUri, $pMethod = '_all_') return false; } + /** + * Detect content type request + */ + private function detectContentType(){ + if (!empty($_SERVER['CONTENT_TYPE']) && strpos($_SERVER['CONTENT_TYPE'], 'application/json') !== false) { + $this->parsePhpInput(); + } + } + + /** + * Parse data php://input to $_POST. It is used in AngularJS + * + * @return $this + */ + private function parsePhpInput(){ + $input = file_get_contents("php://input"); + $data = json_decode($input, true); + if (!empty($data)) foreach($data as $key => $value) + $_POST[$key] = $value; + + return $this; + } }