Php simulates the post request to send the file code

Source: Internet
Author: User
Tags php website
Php simulates the post request to send the file code

Because of project requirements, the local server needs to receive data and then forward the data to another server. Therefore, it is necessary to use a post request to send data. of course, the data also contains file streams.

Curl is one of the common php methods. the general code is as follows:

  1. $ Params1 = "test ";
  2. $ Params2 = "@". $ absolute_path; // if it is a file, the parameter is "@" + absolute path
  3. $ Post_data = array (
  4. 'Params1 '=> $ params1,
  5. 'Params2 '=> $ params2,
  6. );
  7. Function postData ($ url, $ data ){
  8. $ Ch = curl_init ();
  9. $ Timeout = 300;
  10. Curl_setopt ($ ch, CURLOPT_URL, $ url); // request address
  11. // Curl_setopt ($ ch, CURLOPT_REFERER, $ ip); // Construct a route
  12. Curl_setopt ($ ch, CURLOPT_POST, true); // post request
  13. Curl_setopt ($ ch, CURLOPT_BINARYTRANSFER, true); // binary stream
  14. Curl_setopt ($ ch, CURLOPT_POSTFIELDS, $ data); // data
  15. Curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1); // when CURLOPT_RETURNTRANSFER is set to 1, $ head has the returned value of the request.
  16. Curl_setopt ($ ch, CURLOPT_CONNECTTIMEOUT, $ timeout); // you can specify the request timeout value.
  17. $ Handles = curl_exec ($ ch );
  18. Curl_close ($ ch );
  19. Return $ handles;
  20. }


The other party is a java Server. I only know the interface and I don't know how the other party processes the received files. The above method is successful in the Windows wamp environment, but the code fails to be put on the centOS + Nginx server, and the returned message is an error in receiving the file. After packet capture analysis, we found that the formats of the packages delivered by Windows 7 wamp are different from those of the http packages delivered by centos nginx. In general, curl sets content_type to multipart/form-data by default. this is true under win7 wamp on my machine, however, in centos nginx, it is application/x-www-form-urlencoded. Of course, this may also be a problem with server configuration, but I don't know where the problem is. Then I checked the PHP version, which is PHP5.3.X but slightly different. It is not ruled out that the PHP version is a problem. Then add the code:

  1. $ Header = array (
  2. 'Content-Type: multipart/form-data ',
  3. );
  4. Curl_setopt ($ ch, CURLOPT_HTTPHEADER, $ header );


Set the header, but it is still invalid in centos. The content-type cannot be changed.

Later, with the help of the technical director, I saw a link http://php.net/manual/en/class on the official PHP website. curlfile. php, refer to the official website practices in win wamp and centos nginx post requests are successful. After carefully reading the code, I found that the entire http request body was written, instead of the curl self-generated part, and I had to admire it. The following code is released:

  1. Function postData ($ url, $ data = array (), $ data1 = array ()){
  2. $ Header = array (
  3. 'Content-Type: multipart/form-data ',
  4. );
  5. $ Ch = curl_init ();
  6. Curl_setopt ($ ch, CURLOPT_URL, $ url );
  7. Curl_setopt ($ ch, CURLOPT_HTTPHEADER, $ header );
  8. Curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1 );
  9. Curl_setopt ($ ch, CURLOPT_CONNECTTIMEOUT, 10 );
  10. Curl_setopt ($ ch, CURLOPT_BINARYTRANSFER, true );
  11. // Curl_setopt ($ ch, CURLOPT_POSTFIELDS, $ data );
  12. Curl_custom_postfields ($ ch, $ data, $ data1 );
  13. $ Dxycontent = curl_exec ($ ch );
  14. Curl_close ($ ch );
  15. Return $ dxycontent;
  16. }
  17. /**
  18. * For safe multipart POST request for PHP5.3 ~ PHP 5.4.
  19. *
  20. * @ Param resource $ ch cURL resource
  21. * @ Param array $ assoc "name => value"
  22. * @ Param array $ files "name => path"
  23. * @ Return bool
  24. */
  25. Function curl_custom_postfields ($ ch, array $ assoc = array (), array $ files = array ()){
  26. // Invalid characters for "name" and "filename"
  27. Static $ disallow = array ("\ 0", "\" "," \ r "," \ n ");
  28. // Build normal parameters
  29. Foreach ($ assoc as $ k =>v v ){
  30. $ K = str_replace ($ disallow, "_", $ k );
  31. $ Body [] = implode ("\ r \ n", array (
  32. "Content-Disposition: form-data; name = \" {$ k }\"",
  33. "",
  34. Filter_var ($ v ),
  35. ));
  36. }
  37. // Build file parameters
  38. Foreach ($ files as $ k => $ v ){
  39. Switch (true ){
  40. Case false ===$ v = realpath (filter_var ($ v )):
  41. Case! Is_file ($ v ):
  42. Case! Is_readable ($ v ):
  43. Continue; // or return false, throw new InvalidArgumentException
  44. }
  45. $ Data = file_get_contents ($ v );
  46. $ V = call_user_func ("end", explode (DIRECTORY_SEPARATOR, $ v ));
  47. $ K = str_replace ($ disallow, "_", $ k );
  48. $ V = str_replace ($ disallow, "_", $ v );
  49. $ Body [] = implode ("\ r \ n", array (
  50. "Content-Disposition: form-data; name = \" {$ k} \ "; filename = \" {$ v }\"",
  51. "Content-Type: application/octet-stream ",
  52. "",
  53. $ Data,
  54. ));
  55. }
  56. // Generate safe boundary
  57. Do {
  58. $ Boundary = "-------------------". md5 (mt_rand (). microtime ());
  59. } While (preg_grep ("/{$ boundary}/", $ body ));
  60. // Add boundary for each parameters
  61. Array_walk ($ body, function (& $ part) use ($ boundary ){
  62. $ Part = "-- {$ boundary} \ r \ n {$ part }";
  63. });
  64. // Add final boundary
  65. $ Body [] = "-- {$ boundary }--";
  66. $ Body [] = "";
  67. // Set options
  68. Return @ curl_setopt_array ($ ch, array (
  69. CURLOPT_POST => true,
  70. CURLOPT_POSTFIELDS => implode ("\ r \ n", $ body ),
  71. CURLOPT_HTTPHEADER => array (
  72. "Secondary CT: 100-continue ",
  73. "Content-Type: multipart/form-data; boundary = {$ boundary}", // change Content-Type
  74. ),
  75. ));
  76. }


Parameter transfer is not affected. if the file is in the absolute path, + "@". The only difference is that the file data and common data are distinguished by different arrays, and different processing is performed when simulating the http body part. Finally, the file is successfully uploaded.

Php, post

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.