MultipartFormDataParser.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. namespace Libs;
  3. use Psr\Http\Message\ServerRequestInterface;
  4. class MultipartFormDataParser
  5. {
  6. public static function parse(ServerRequestInterface $request): array
  7. {
  8. $contentType = $request->getHeaderLine('Content-Type');
  9. if (!preg_match('/multipart\/form-data;\s*boundary=(?:(?:"([^"]+)")|([^;\s]+))/i', $contentType, $m)) {
  10. throw new \RuntimeException('Invalid multipart Content-Type');
  11. }
  12. $boundary = (isset($m[1]) && $m[1] !== '') ? $m[1] : ($m[2] ?? '');
  13. if ($boundary === '') {
  14. throw new \RuntimeException('Missing multipart boundary');
  15. }
  16. $rawBody = (string)$request->getBody();
  17. if ($rawBody === '') {
  18. $rawBody = (string)file_get_contents('php://input');
  19. }
  20. $delimiter = "--" . $boundary;
  21. $parts = explode($delimiter, $rawBody);
  22. $fields = [];
  23. $files = [];
  24. foreach ($parts as $part) {
  25. $part = ltrim($part, "\r\n");
  26. $part = rtrim($part, "\r\n");
  27. if ($part === '' || $part === '--') {
  28. continue;
  29. }
  30. $split = preg_split("/\r?\n\r?\n/", $part, 2);
  31. if (!$split || count($split) !== 2) {
  32. continue;
  33. }
  34. [$rawHeaders, $body] = $split;
  35. $headers = self::parseHeaders($rawHeaders);
  36. $cd = $headers['content-disposition'] ?? '';
  37. if (!preg_match('/name="([^"]+)"/i', $cd, $nm)) {
  38. continue;
  39. }
  40. $name = $nm[1];
  41. $filename = null;
  42. if (preg_match('/filename="([^"]*)"/i', $cd, $fm)) {
  43. $filename = $fm[1];
  44. }
  45. $body = preg_replace("/\r\n\z/", '', $body);
  46. if ($filename !== null && $filename !== '') {
  47. $files[$name] = [
  48. 'field' => $name,
  49. 'filename' => $filename,
  50. 'content_type' => $headers['content-type'] ?? 'application/octet-stream',
  51. 'content' => $body,
  52. ];
  53. } else {
  54. $fields[$name] = $body;
  55. }
  56. }
  57. return ['fields' => $fields, 'files' => $files];
  58. }
  59. private static function parseHeaders(string $rawHeaders): array
  60. {
  61. $headers = [];
  62. foreach (preg_split('/\r?\n/', $rawHeaders) as $line) {
  63. $line = trim($line);
  64. if ($line === '' || strpos($line, ':') === false) {
  65. continue;
  66. }
  67. [$k, $v] = explode(':', $line, 2);
  68. $headers[strtolower(trim($k))] = trim($v);
  69. }
  70. return $headers;
  71. }
  72. }