簡體   English   中英

PHP 中 API 的 PUT 請求和變量

[英]PUT requests and variables for API in PHP

我目前正在構建一個 API,我想將更新(我使用 POST 用於)與創建(我想使用 PUT 用於)分開。 這似乎是一個愚蠢的問題,但如何檢索通過 PUT 發送的變量? PHP 中沒有 $_PUT 數組。 我正在嘗試以這種方式使用 WFetch 發送數據:

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

我試圖查找如何使用 PUT,但我似乎無法弄清楚。

使用以下$_PUT在 PHP 中創建$_PUT數組:

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

現在您可以使用$_PUT['Name']來獲取"Test"

使用$_REQUEST["your target"]訪問通過 PUT 請求發送的數據

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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM