file_get_contents('php://input') always returns an empty string

后端 未结 12 2150
遥遥无期
遥遥无期 2020-12-09 09:04

I\'m building a PHP RESTful API, following this tutorial. The following function, which should return the data sent with the request when the \'put\' method is used, returns

12条回答
  •  有刺的猬
    2020-12-09 09:45

    Edit as you wish

    function getPostObject() {
        $str = file_get_contents('php://input');
        $std = json_decode($str);
        if ($std === null) {
            $std = new stdClass();
            $array = explode('&', $str);
            foreach ($array as $parm) {
                $parts = explode('=', $parm);
                if(sizeof($parts) != 2){
                    continue;
                }
                $key = $parts[0];
                $value = $parts[1];
                if ($key === NULL) {
                    continue;
                }
                if (is_string($key)) {
                    $key = urldecode($key);
                } else {
                    continue;
                }
                if (is_bool($value)) {
                    $value = boolval($value);
                } else if (is_numeric($value)) {
                    $value += 0;
                } else if (is_string($value)) {
                    if (empty($value)) {
                        $value = null;
                    } else {
                        $lower = strtolower($value);
                        if ($lower === 'true') {
                            $value = true;
                        } else if ($lower === 'false') {
                            $value = false;
                        } else if ($lower === 'null') {
                            $value = null;
                        } else {
                            $value = urldecode($value);
                        }
                    }
                } else if (is_array($value)) {
                    // value is an array
                } else if (is_object($value)) {
                    // value is an object
                }
                $std->$key = $value;
            }
            // length of post array
            //$std->length = sizeof($array);
        }
        return $std;
    }
    

提交回复
热议问题