PHP analog POST request send file code

Source: Internet
Author: User
Tags php website

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

Curl is one of the most common ways PHP is used, and the general code is as follows:

    1. $params 1 = "Test";
    2. $params 2 = "@". $absolute _path;//if it is a file, the parameter is "@" + absolute path
    3. $post _data = Array (
    4. ' Params1 ' = $params 1,
    5. ' Params2 ' = $params 2,
    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);//Construction 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 o'clock $head has the requested return value
    16. curl_setopt ($ch, Curlopt_connecttimeout, $timeout); Set the request time-out period
    17. $handles = curl_exec ($ch);
    18. Curl_close ($ch);
    19. return $handles;
    20. }
Copy Code
The other side is the Java server, I only know the interface, do not know how to handle the file received. The above approach was successful in the Win7 Wamp environment, but it failed to put the code on the Centos+nginx server, and the message returned was that the file received failed. After grasping the packet analysis, found in Win7 Wamp issued by the package and CentOS Nginx issued by the HTTP packet format is different. In general, curl defaults to Content_Type set to Multipart/form-data, on my machine Win7 Wamp, but the CentOS Nginx is application/ X-www-form-urlencoded. Of course this may be a server configuration problem, but I don't know where the problem is. Then I looked at the next PHP version, the same as php5.3.x, but with a slight difference. Also does not exclude is the PHP version of the problem. Then add the code:
    1. $header = Array (
    2. ' Content-type:multipart/form-data ',
    3. );
    4. curl_setopt ($ch, Curlopt_httpheader, $header);
Copy Code
The header is set, but it still does not work under CentOS. Can not change the content-type, it is the pit father.

Later, with the help of the technical Director, read a link on the official PHP website http://php.net/manual/en/class.curlfile.php, referring to the official website practice in the win Wamp and CentOS Nginx POST request has been successful. Read the code carefully, found that the procedure was completely written in the body of the HTTP request, rather than curl their own generated parts, have to admire. Release the code below:

  1. function PostData ($url, $data = Array (), $data 1 = 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, $data 1);
  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 ("\", "\" "," \ r "," \ n ");
  28. Build normal parameters
  29. foreach ($assoc as $k = = $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. "Expect:100-continue",
  73. "Content-type:multipart/form-data; boundary={$boundary} ",//Change Content-type
  74. ),
  75. ));
  76. }
Copy Code
Parameter passing has no effect, if the file is before the absolute path + "@". The only difference is that the file data and the normal data are distinguished by different arrays, which are handled differently when simulating the body part of HTTP. Finally, the file is uploaded successfully.
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.