Passing $_POST values with cURL

后端 未结 8 1587
野的像风
野的像风 2020-11-22 16:21

How do you pass $_POST values to a page using cURL?

相关标签:
8条回答
  • 2020-11-22 17:01

    Should work fine.

    $data = array('name' => 'Ross', 'php_master' => true);
    
    // You can POST a file by prefixing with an @ (for <input type="file"> fields)
    $data['file'] = '@/home/user/world.jpg';
    
    $handle = curl_init($url);
    curl_setopt($handle, CURLOPT_POST, true);
    curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
    curl_exec($handle);
    curl_close($handle)
    

    We have two options here, CURLOPT_POST which turns HTTP POST on, and CURLOPT_POSTFIELDS which contains an array of our post data to submit. This can be used to submit data to POST <form>s.


    It is important to note that curl_setopt($handle, CURLOPT_POSTFIELDS, $data); takes the $data in two formats, and that this determines how the post data will be encoded.

    1. $data as an array(): The data will be sent as multipart/form-data which is not always accepted by the server.

      $data = array('name' => 'Ross', 'php_master' => true);
      curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
      
    2. $data as url encoded string: The data will be sent as application/x-www-form-urlencoded, which is the default encoding for submitted html form data.

      $data = array('name' => 'Ross', 'php_master' => true);
      curl_setopt($handle, CURLOPT_POSTFIELDS, http_build_query($data));
      

    I hope this will help others save their time.

    See:

    • curl_init
    • curl_setopt
    0 讨论(0)
  • 2020-11-22 17:01

    Check out the cUrl PHP documentation page. It will help much more than just with example scripts.

    0 讨论(0)
提交回复
热议问题