1

我目前正在构建一个 API,我想将更新(我正在使用 POST)与创建(我想使用 PUT)分开。这似乎是一个愚蠢的问题,但我如何检索通过 PUT 发送的变量?PHP 中没有 $_PUT 数组。我正在尝试以这种方式使用 WFetch 发送数据:

Content-Type: application/x-www-form-urlencoded\r\n
\r\n
Name=Test\r\n

我试图查找如何使用 PUT,但我似乎无法弄清楚。

4

3 回答 3

1

使用以下命令$_PUT在 PHP 中创建数组:

parse_str(file_get_contents('php://input'), $_PUT);

现在您可以$_PUT['Name']使用"Test".

于 2013-08-26T14:33:14.350 回答
0

用于$_REQUEST["your target"]访问通过 PUT 请求发送的数据

于 2020-07-08T17:53:43.713 回答
0

PHP put 给了我很多时间,这个函数会节省一些人的时间:

function parsePutRequest()
    {
        // Fetch content and determine boundary
        $raw_data = file_get_contents('php://input');
        $boundary = substr($raw_data, 0, strpos($raw_data, "\r\n"));

    // Fetch each part
    $parts = array_slice(explode($boundary, $raw_data), 1);
    $data = array();

    foreach ($parts as $part) {
        // If this is the last part, break
        if ($part == "--\r\n") break; 

        // Separate content from headers
        $part = ltrim($part, "\r\n");
        list($raw_headers, $body) = explode("\r\n\r\n", $part, 2);

        // Parse the headers list
        $raw_headers = explode("\r\n", $raw_headers);
        $headers = array();
        foreach ($raw_headers as $header) {
            list($name, $value) = explode(':', $header);
            $headers[strtolower($name)] = ltrim($value, ' '); 
        } 

        // Parse the Content-Disposition to get the field name, etc.
        if (isset($headers['content-disposition'])) {
            $filename = null;
            preg_match(
                '/^(.+); *name="([^"]+)"(; *filename="([^"]+)")?/', 
                $headers['content-disposition'], 
                $matches
            );
            list(, $type, $name) = $matches;
            isset($matches[4]) and $filename = $matches[4]; 

            // handle your fields here
            switch ($name) {
                // this is a file upload
                case 'userfile':
                    file_put_contents($filename, $body);
                    break;

                // default for all other files is to populate $data
                default: 
                    $data[$name] = substr($body, 0, strlen($body) - 2);
                    break;
            } 
        }

    }
    return $data;
}
于 2020-09-17T14:09:44.203 回答