Advertisement
Guest User

Untitled

a guest
Sep 22nd, 2017
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.28 KB | None | 0 0
  1. <?php
  2. /**
  3. * Build multipart/form-data
  4. *
  5. * @param array @$data Data
  6. * @param array @$files 1-D array of files where key is field name and value if file contents
  7. * @param string &$contentType Retun variable for content type
  8. *
  9. * @return string Encoded data
  10. */
  11. function buildMultipartFormData(array &$data, array &$files, &$contentType)
  12. {
  13. $eol = "\r\n";
  14.  
  15. // Build test string
  16. $testStr = '';
  17. array_walk_recursive($data, function($item, $key) use (&$testStr, &$eol) {
  18. $testStr .= $key . $eol . $item . $eol;
  19. });
  20.  
  21. // Get file content type and content. Add to test string
  22. $finfo = finfo_open(FILEINFO_MIME_TYPE);
  23. $fileContent = array();
  24. $fileContentTypes = array();
  25. foreach ($files as $key=>$filename)
  26. {
  27. $fileContent[$key] = file_get_contents($filename);
  28. $fileContentTypes[$key] = finfo_file($finfo, $filename);
  29. $testStr .= $key . $eol . $fileContentTypes[$key] . $eol. $fileContent[$key] . $eol;
  30. }
  31. finfo_close($finfo);
  32.  
  33. // Find a boundary not present in the test string
  34. $boundaryLen = 6;
  35. $alpha = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  36. do {
  37. $boundary = '--';
  38. for ($i = 0; $i < $boundaryLen; $i++)
  39. {
  40. $c = rand(0, 61);
  41. $boundary .= $alpha[$c];
  42. }
  43.  
  44. // Check test string
  45. if (strpos($testStr, $boundary) !== false)
  46. {
  47. $boundary = null;
  48. $boundaryLen++;
  49. }
  50. } while ($boundary === null);
  51. unset($testStr);
  52.  
  53. // Set content type
  54. $contentType = 'multipart/form-data, boundary='.$boundary;
  55.  
  56. // Build data
  57. $rtn = '';
  58. $func = function($data, $baseKey = null) use (&$func, &$boundary, &$eol)
  59. {
  60. $rtn = '';
  61. foreach ($data as $key=>&$value)
  62. {
  63. // Get key
  64. $key = $baseKey === null ? $key : ($baseKey . '[' . $key . ']');
  65.  
  66. // Add data
  67. if (is_array($value))
  68. $rtn .= $func($value, $key);
  69. else
  70. $rtn .= '--' . $boundary . $eol . 'Content-Disposition: form-data; name="'.$key.'"' . $eol . $eol . $value . $eol;
  71. }
  72.  
  73. return $rtn;
  74. };
  75. $rtn = $func($data);
  76.  
  77. // Add files
  78. foreach ($files as $key=>$filename)
  79. {
  80. $rtn .= '--' . $boundary . $eol . 'Content-Disposition: file; name="'.$key.'"; filename="'.basename($filename).'"' . $eol
  81. . 'Content-Type: ' . $fileContentTypes[$key] . $eol
  82. . 'Content-Transfer-Encoding: binary' . $eol . $eol
  83. . $fileContent[$key] . $eol;
  84. }
  85.  
  86. return $rtn . '--' . $boundary . '--' . $eol;
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement