Helper.php 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. <?php
  2. namespace app\common\services\qcloud;
  3. class Helper {
  4. /**
  5. * Build custom post fields for safe multipart POST request for php before 5.5.
  6. * @param $fields array of key -> value fields to post.
  7. * @return $boundary and encoded post fields.
  8. */
  9. public static function yz_buildCustomPostFields($fields) {
  10. // invalid characters for "name" and "filename"
  11. static $disallow = array("\0", "\"", "\r", "\n");
  12. // initialize body
  13. $body = array();
  14. // build normal parameters
  15. foreach ($fields as $key => $value) {
  16. $key = str_replace($disallow, "_", $key);
  17. $body[] = implode("\r\n", array(
  18. "Content-Disposition: form-data; name=\"{$key}\"",
  19. '',
  20. filter_var($value),
  21. ));
  22. }
  23. // generate safe boundary
  24. do {
  25. $boundary = "---------------------" . md5(mt_rand() . microtime());
  26. } while (preg_grep("/{$boundary}/", $body));
  27. // add boundary for each parameters
  28. foreach ($body as &$part) {
  29. $part = "--{$boundary}\r\n{$part}";
  30. }
  31. unset($part);
  32. // add final boundary
  33. $body[] = "--{$boundary}--";
  34. $body[] = '';
  35. return array($boundary, implode("\r\n", $body));
  36. }
  37. }