public function parse($rawBody, $contentType)
{
if (!empty($_POST) || !empty($_FILES)) {
// normal POST request is parsed by PHP automatically
return $_POST;
}
if (empty($rawBody)) {
return [];
}
if (!preg_match('/boundary=(.*)$/is', $contentType, $matches)) {
return [];
}
$boundary = $matches[1];
$bodyParts = preg_split('/-+' . preg_quote($boundary) . '/s', $rawBody);
array_pop($bodyParts);
// last block always has no data, contains boundary ending like `--`
$bodyParams = [];
$filesCount = 0;
foreach ($bodyParts as $bodyPart) {
if (empty($bodyPart)) {
continue;
}
list($headers, $value) = preg_split("/\\R\\R/", $bodyPart, 2);
$headers = $this->parseHeaders($headers);
if (!isset($headers['content-disposition']['name'])) {
continue;
}
if (isset($headers['content-disposition']['filename'])) {
// file upload:
if ($filesCount >= $this->getUploadFileMaxCount()) {
continue;
}
$fileInfo = ['name' => $headers['content-disposition']['filename'], 'type' => ArrayHelper::getValue($headers, 'content-type', 'application/octet-stream'), 'size' => StringHelper::byteLength($value), 'error' => UPLOAD_ERR_OK, 'tmp_name' => null];
if ($fileInfo['size'] > $this->getUploadFileMaxSize()) {
$fileInfo['error'] = UPLOAD_ERR_INI_SIZE;
} else {
$tmpResource = tmpfile();
if ($tmpResource === false) {
$fileInfo['error'] = UPLOAD_ERR_CANT_WRITE;
} else {
$tmpResourceMetaData = stream_get_meta_data($tmpResource);
$tmpFileName = $tmpResourceMetaData['uri'];
if (empty($tmpFileName)) {
$fileInfo['error'] = UPLOAD_ERR_CANT_WRITE;
@fclose($tmpResource);
} else {
fwrite($tmpResource, $value);
$fileInfo['tmp_name'] = $tmpFileName;
$fileInfo['tmp_resource'] = $tmpResource;
// save file resource, otherwise it will be deleted
}
}
}
$this->addFile($_FILES, $headers['content-disposition']['name'], $fileInfo);
$filesCount++;
} else {
// regular parameter:
$this->addValue($bodyParams, $headers['content-disposition']['name'], $value);
}
}
return $bodyParams;
}