使用PHP手动解析原始的multipartform-data数据

使用PHP手动解析原始的multipartform-data数据,第1张

使用PHP手动解析原始的multipart / form-data数据

编辑-请先阅读:
此答案在7年后仍然很受欢迎。从那时起,我就再也没有使用过此代码,并且不知道这些天是否有更好的方法。请查看下面的注释,并了解在许多情况下此代码将无法工作。使用风险自负。

-

好的,因此,根据Dave和Everts的建议,我决定手动解析原始请求数据。经过大约一天的搜索,我没有找到其他方法来执行此 *** 作。

我没有像在引用线程中那样篡改原始数据,因为那样会破坏正在上传的文件。这就是正则表达式。测试的效果不是很好,但似乎适用于我的工作案例。事不宜迟,并希望有一天能对其他人有所帮助:

function parse_raw_http_request(array &$a_data){  // read incoming data  $input = file_get_contents('php://input');  // grab multipart boundary from content type header  preg_match('/boundary=(.*)$/', $_SERVER['CONTENT_TYPE'], $matches);  $boundary = $matches[1];  // split content by boundary and get rid of last -- element  $a_blocks = preg_split("/-+$boundary/", $input);  array_pop($a_blocks);  // loop data blocks  foreach ($a_blocks as $id => $block)  {    if (empty($block))      continue;    // you'll have to var_dump $block to understand this and maybe replace n or r with a visibile char    // 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]+([^nr].*)?$/s", $block, $matches);    }    // parse all other fields    else    {      // match "name" and optional value in between newline sequences      preg_match('/name="([^"]*)"[n|r]+([^nr].*)?r$/s', $block, $matches);    }    $a_data[$matches[1]] = $matches[2];  }        }

通过引用使用(以免在数据周围复制过多):

$a_data = array();parse_raw_http_request($a_data);var_dump($a_data);


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5602400.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存