POST JSON data via CURL and grabbing it

前端 未结 2 1849
[愿得一人]
[愿得一人] 2020-12-29 16:48

I am trying to pass a json data as param for cURL POST. However, I am stuck at grabbing it and saving it on db.

cURL file:

$data = array(\"name\" =&g         


        
相关标签:
2条回答
  • 2020-12-29 17:02

    Use following php function for posting data using php curl function in x-www-form-urlencoded format.

    <?php
        $bodyData = http_build_query($data); //for x-www-form-urlencoded
    ?>
    
    0 讨论(0)
  • 2020-12-29 17:14

    You are sending the data as raw JSON in the body, it will not populate the $_POST variable.

    You need to do one of two things:

    1. You can change the content type to one that will populate the $_POST array
    2. You can read the raw body data.

    I would recommend option two if you have control over both ends of the communication, as it will keep the request body size to a minimum and save bandwidth over time. (Edit: I didn't really emphasize here that the amount of bandwidth it will save is negligible, only a few bytes per request, this would only be a valid concern is very high traffic environments. However I still recommend option two because it is the cleanest way)

    In your test_curl file, do this:

    $fp = fopen('php://input', 'r');
    $rawData = stream_get_contents($fp);
    
    $postedJson = json_decode($rawData);
    
    var_dump($postedJson);
    

    If you want to populate the $_POST variable, you will need to change the way you send the data to the server:

    $data = array (
      'name' => 'Hagrid',
      'age' => '36'
    );
    
    $bodyData = array (
      'json' => json_encode($data)
    );
    $bodyStr = http_build_query($bodyData);
    
    $url = 'http://localhost/project/test_curl';
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
      'Content-Type: application/x-www-form-urlencoded',
      'Content-Length: '.strlen($bodyStr)
    ));
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $bodyStr);
    
    $result = curl_exec($ch);
    

    The raw, undecoded JSON will now be available in $_POST['json'].

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