merge_php_input.php
<?php
/**
* 使用fetch异步请求数据,数据需要使用php://input来获取
* 此方法将php://input数据并入$_REQUEST
*
* @author Jason
* @DateTime 2017-12-04 13:51
* @access public
* @return array
*/
function merge_php_input() {
// 请求方法
$method = PHP_SAPI == 'cli' ? 'GET' : $_SERVER['REQUEST_METHOD'];
// php input流数据
$content = file_get_contents('php://input');
// 获取请求的content type
$contentType = $_SERVER['CONTENT_TYPE'];
if ($contentType) {
if (strpos($contentType, ';')) {
list($type) = explode(';', $contentType);
} else {
$type = $contentType;
}
$contentType = trim($type);
}
// 自动获取请求变量
switch ($method) {
case 'POST': {
if (empty($_POST) && false !== strpos($contentType, 'application/json')) {
$vars = (array) json_decode($content, true);
$_POST = $vars;
} else {
$vars = $_POST;
}
} break;
case 'PUT':
case 'DELETE':
case 'PATCH':{
if (false !== strpos($contentType, 'application/json')) {
$vars = (array) json_decode($content, true);
} else {
parse_str($content, $vars);
}
} break;
default:
$vars = [];
}
// 当前请求参数和URL地址中的参数合并
$_REQUEST = array_merge($_REQUEST, $_GET, $vars);
return $_REQUEST;
}