How to POST JSON Data With PHP cURL?

前端 未结 7 2194
失恋的感觉
失恋的感觉 2020-11-22 10:02

Here is my code,

$url = \'url_to_post\';
$data = array(
    \"first_name\" => \"First name\",
    \"last_name\" => \"last name\",
    \"email\"=>\"e         


        
7条回答
  •  无人及你
    2020-11-22 10:25

    First,

    1. always define certificates with CURLOPT_CAPATH option,

    2. decide how your POSTed data will be transfered.

    1 Certificates

    By default:

    • CURLOPT_SSL_VERIFYHOST == 2 which "checks the existence of a common name and also verify that it matches the hostname provided" and

    • CURLOPT_VERIFYPEER == true which "verifies the peer's certificate".

    So, all you have to do is:

    const CAINFO = SERVER_ROOT . '/registry/cacert.pem';
    ...
    \curl_setopt($ch, CURLOPT_CAINFO, self::CAINFO);
    

    taken from a working class where SERVER_ROOT is a constant defined during application bootstraping like in a custom classloader, another class etc.

    Forget things like \curl_setopt($handler, CURLOPT_SSL_VERIFYHOST, 0); or \curl_setopt($handler, CURLOPT_SSL_VERIFYPEER, 0);.

    Find cacert.pem there as seen in this question.

    2 POST modes

    There are actually 2 modes when posting data:

    • the data is transfered with Content-Type header set to multipart/form-data or,

    • the data is a urlencoded string with application/x-www-form-urlencoded encoding.

    In the first case you pass an array while in the second you pass a urlencoded string.

    multipart/form-data ex.:

    $fields = array('a' => 'sth', 'b' => 'else');
    $ch = \curl_init();
    \curl_setopt($ch, CURLOPT_POST, 1);
    \curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
    

    application/x-www-form-urlencoded ex.:

    $fields = array('a' => 'sth', 'b' => 'else');
    $ch = \curl_init();
    \curl_setopt($ch, CURLOPT_POST, 1);
    \curl_setopt($ch, CURLOPT_POSTFIELDS, \http_build_query($fields));
    

    http_build_query:

    Test it at your command line as

    user@group:$ php -a
    php > $fields = array('a' => 'sth', 'b' => 'else');
    php > echo \http_build_query($fields);
    a=sth&b=else
    

    The other end of the POST request will define the appropriate mode of connection.

提交回复
热议问题