Last active
August 29, 2015 14:01
-
-
Save felipevolpatto/544c89fdaa83b158a9db to your computer and use it in GitHub Desktop.
Manually parse raw HTTP data with PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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