Skip to content

Instantly share code, notes, and snippets.

@felipevolpatto
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save felipevolpatto/544c89fdaa83b158a9db to your computer and use it in GitHub Desktop.
Save felipevolpatto/544c89fdaa83b158a9db to your computer and use it in GitHub Desktop.
Manually parse raw HTTP data with PHP
<?php
function parseRawHttpRequest(array &$arrayData) {
$input = file_get_contents('php://input');
preg_match('/boundary=(.*)$/', $_SERVER['CONTENT_TYPE'], $matches);
if (!count($matches)) {
// parse_str(urldecode($input), $arrayData);
parse_str($input, $arrayData);
return $arrayData;
}
$boundary = $matches[1];
// split content by boundary and get rid of last -- element
$arrayBlocks = preg_split("/-+$boundary/", $input);
array_pop($arrayBlocks);
// loop data blocks
foreach ($arrayBlocks as $id => $block) {
if (empty($block))
continue;
// parse uploaded files
if (strpos($block, 'application/octet-stream') !== FALSE) {
// match "name", then everything after "stream" (optional) except for prepending newlines
preg_match("/name=\"([^\"]*)\".*stream[\n|\r]+([^\n\r].*)?$/s", $block, $matches);
$arrayData['files'][$matches[1]] = $matches[2];
} else {
// match "name" and optional value in between newline sequences
preg_match('/name=\"([^\"]*)\"[\n|\r]+([^\n\r].*)?\r$/s', $block, $matches);
$arrayData[$matches[1]] = $matches[2];
}
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment