人人商城

libcurl_helper.php 1.1KB

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