接受的答案將不適用於multipart/form-data
,出於無奈,我寫了我自己的方法。這處理文件上傳和多維請求。
/**
* @param string $formData Raw response request of type FormData
* @param array $header Meta data for each part of the form data (optional)
* @return array Processed form data
*/
public function parse_form_data($formData, &$header)
{
$endOfFirstLine = strpos($formData, "\r\n");
$boundary = substr($formData, 0, $endOfFirstLine);
// Split form-data into each entry
$parts = explode($boundary, $formData);
$return = [];
$header = [];
// Remove first and last (null) entries
array_shift($parts);
array_pop($parts);
foreach ($parts as $part) {
$endOfHead = strpos($part, "\r\n\r\n");
$startOfBody = $endOfHead + 4;
$head = substr($part, 2, $endOfHead - 2);
$body = substr($part, $startOfBody, -2);
$headerParts = preg_split('#; |\r\n#', $head);
$key = null;
$thisHeader = [];
// Parse the mini headers,
// obtain the key
foreach ($headerParts as $headerPart) {
if (preg_match('#(.*)(=|:)(.*)#', $headerPart, $keyVal)) {
if ($keyVal[1] == "name") $key = substr($keyVal[3], 1, -1);
else {
if($keyVal[2] == "="){
$thisHeader[$keyVal[1]] = substr($keyVal[3], 1, -1);
}else{
$thisHeader[$keyVal[1]] = $keyVal[3];
}
}
}
}
// If the key is multidimensional,
// generate multidimentional array
// based off of the parts
$nameParts = preg_split('#(?=\[.*\])#', $key);
if (count($nameParts) > 1) {
$current = &$return;
$currentHeader = &$header;
$l = count($nameParts);
for ($i = 0; $i < $l; $i++) {
// Strip array access tokens
$namePart = preg_replace('#[\[\]]#', "", $nameParts[$i]);
// If we are at the end of the depth of this entry,
// add data to array
if ($i == $l - 1) {
if (isset($thisHeader['filename'])) {
$filename = tempnam(sys_get_temp_dir(), "php");
file_put_contents($filename, $body);
$current[$namePart] = [
"name" => $thisHeader['filename'],
"type" => $thisHeader['Content-Type'],
"tmp_name" => $filename,
"error" => 0,
"size" => count($body)
];
} else {
$current[$namePart] = $body;
}
$currentHeader[$namePart] = $thisHeader;
} else {
// Advance into the array
if (!isset($current[$namePart])) {
$current[$namePart] = [];
$currentHeader[$namePart] = [];
}
$current = &$current[$namePart];
$currentHeader = &$currentHeader[$namePart];
}
}
} else {
if (isset($thisHeader['filename'])) {
$filename = tempnam(sys_get_temp_dir(), "php");
file_put_contents($filename, $body);
$return[$key] = [
"name" => $thisHeader['filename'],
"type" => $thisHeader['Content-Type'],
"tmp_name" => $filename,
"error" => 0,
"size" => count($body)
];
} else {
$return[$key] = $body;
}
$return[$key] = $body;
$header[$key] = $thisHeader;
}
}
return $return;
}
難道不取決於更容易地使用,代替通用捲曲擴展[HTTP擴展](http://de.php.net/manual/en/book.http.php)? – Gordon
嗯,我從來不知道!感謝您的鏈接。 – john
你的意思是'$ params'是空的嗎? –