Reputation: 1773
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.
Upvotes: 1
Views: 3408
Reputation: 4534
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;
}
Upvotes: 1
Reputation: 1
Use $_REQUEST["your target"]
to access data sent through PUT request
Upvotes: 0
Reputation: 50
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"
.
Upvotes: 0