简体   繁体   中英

PUT requests and variables for API in PHP

I'm currently building an API, and I want to separate updating (Which I am using POST for) from creation (Which I want to use PUT for). This might seem like a dumb question, but how do I retrieve variables sent through PUT? There is no $_PUT array in PHP. I'm trying to send data with WFetch this way:

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

I've tried to look up how to use PUT, but I can't seem to figure it out.

Use the following to create the $_PUT array in PHP:

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

Now you can use $_PUT['Name'] to get "Test" .

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

PHP put has given me tough time, this function will save someone's time:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM