thecodeholic / tc-php-mvc-core

103 stars 30 forks source link

Function getBody() is not able to read body of a post request sent as application/json #7

Open ibrahimesseddyq opened 2 years ago

ibrahimesseddyq commented 2 years ago

I tried to to interact with the mvc using postman and i findout that it cant read json formatted request You need to check if the upcoming request is post and sent as application/json, and then read the body request using 'file_get_contents('php://input'); in Request getBody Method then parse it into object

Tusbahle commented 2 years ago

because you are using form input only. if you want to get json data write this format

public function getBody()
    {
        $data = [];
        if ($this->isGet()) {
            foreach ($_GET as $key => $value) {
                $data[$key] = filter_input(INPUT_GET, $key, FILTER_SANITIZE_SPECIAL_CHARS);
            }
        }
        if ($this->isPost()) {
            if ($this->isJSON()) {
                $content = trim(file_get_contents("php://input"));
                return json_decode($content);
            }

            foreach ($_POST as $key => $value) {
                echo $key;
                $data[$key] = filter_input(INPUT_POST, $key, FILTER_SANITIZE_SPECIAL_CHARS);
            }
        }
        return $data;
    }
   public function isJSON()
    {
      $contentType = isset($_SERVER["CONTENT_TYPE"]) ? strtolower($_SERVER["CONTENT_TYPE"]) : '';
        return   $contentType === 'application/json';
    }

now you can get json data & form data as well that is all