![](/img/trans.png)
[英]PUT and DELETE requests unsuccessful on PHP REST API, but POST and GET are fine
[英]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.