Facebook Twitter Instagram
    TecAdmin
    • Home
    • FeedBack
    • Submit Article
    • About Us
    Facebook Twitter Instagram
    TecAdmin
    You are at:Home»Programming»PHP»How To POST JSON Data with PHP cURL

    How To POST JSON Data with PHP cURL

    By RahulFebruary 25, 20233 Mins Read

    When working with APIs, it’s common to send and receive data in JSON format. In PHP, you can use the cURL library to send HTTP requests, including sending JSON data in a POST request. In this article, we’ll show you how to POST JSON data with PHP cURL in a step-by-step guide.

    Advertisement

    Step 1: Set the URL and JSON data

    The first step is to set the URL that you want to send the request to and the JSON data that you want to send in the request body. For this example, we’ll use a sample JSON data:

    1
    2
    3
    4
    5
    6
    7
    $data = array(
        'name' => 'John Doe',
        'email' => '[email protected]',
        'phone' => '1234567890'
    );
     
    $json = json_encode($data);

    In this example, we’ve created an array of data and encoded it into a JSON string using the json_encode() function.

    Step 2: Set the cURL options

    The next step is to set the cURL options for the request, including the URL, request method, and request body. Here’s an example of how to set the cURL options:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    $url = 'https://example.com/api/create';
    $ch = curl_init($url);
     
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Content-Length: ' . strlen($json)
    ));

    In this example, we’ve set the following options:

    • CURLOPT_RETURNTRANSFER: Set to true to return the response as a string instead of outputting it directly to the screen.
    • CURLOPT_CUSTOMREQUEST: Set to “POST” to specify that we’re sending a POST request.
    • CURLOPT_POSTFIELDS: Set to the JSON data that we want to send in the request body.
    • CURLOPT_HTTPHEADER: Set to an array of headers, including the Content-Type header to specify that we’re sending JSON data, and the Content-Length header to specify the length of the JSON data.

    Step 3: Send the request and handle the response

    The final step is to send the request using the curl_exec() function and handle the response. Here’s an example of how to do this:

    1
    2
    3
    4
    5
    6
    7
    $response = curl_exec($ch);
    if(curl_errno($ch)) {
        echo 'Error: ' . curl_error($ch);
    } else {
        echo $response;
    }
    curl_close($ch);

    In this example, we’ve used the curl_exec() function to send the request and store the response in the $response variable. We’ve also checked for any errors using the curl_errno() function and displayed the error message if there was an error. Finally, we’ve closed the cURL handle using the curl_close() function.

    Step 4: Complete PHP Script

    After combining the above code, you will get a full functional PHP script that can POST JSON data to remote APIs.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    <?php
     
    $data = array(
        'name' => 'John Doe',
        'email' => '[email protected]',
        'phone' => '1234567890'
    );
     
    $json = json_encode($data);
    $url = 'https://example.com/api/create';
    $ch = curl_init($url);
     
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Content-Length: ' . strlen($json)
    ));
     
    $response = curl_exec($ch);
    if(curl_errno($ch)) {
        echo 'Error: ' . curl_error($ch);
    } else {
        echo $response;
    }
    curl_close($ch);
     
    ?>

    Save the file content and run this via the PHP command line interface.

    Conclusion

    In this article, we’ve shown you how to POST JSON data with PHP cURL in a step-by-step guide. By setting the URL and JSON data, setting the cURL options, and sending the request, and handling the response, you can easily send JSON data in a POST request using PHP cURL.

    curl libcurl PHP
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email WhatsApp

    Related Posts

    How to Prevent SQL-injection in PHP using Prepared Statements

    Preventing SQL injection attacks with prepared statements in MySQL

    PHP Arrays: A Beginner’s Guide

    View 12 Comments

    12 Comments

    1. James R. Buzzell on July 30, 2021 4:32 pm

      nice This was very helpful! Thanks for posting!

      Reply
    2. 3rewdf on April 6, 2021 9:19 am

      The main thing is that the request must be a POST request with properly json-encoded data in the body. The headers must properly describe the post body.

      Reply
    3. ioio on October 30, 2019 9:02 am

      very helpful,
      thank you

      Reply
    4. David on October 24, 2019 4:46 pm

      Is there a way to avoid the auto “Content-Type: application/x-www-form-urlencoded
      ” when using POST, I mean, I’m using the following code:
      //—————————————————————————————————-
      $ch = curl_init();
      if(!empty($gdxParams))
      {
      $curlUrl=$curlUrl.’?’.$gdxParams;
      }
      $curlOptions=array();
      if($gdxMethod==”POST”)
      {
      $curlOptions=[
      CURLOPT_HTTPHEADER=>[
      ‘x-api-key: ‘.$gdxApiKey,
      ‘Authorization: Bearer ‘.$gdxApiKey,
      ‘Content-Type​: ​application/json’,
      ],
      CURLOPT_URL=>$curlUrl,
      CURLOPT_CUSTOMREQUEST=>’POST’,
      CURLOPT_POSTFIELDS=>json_encode($gdxArrayParams),
      CURLOPT_RETURNTRANSFER=>true,
      CURLINFO_HEADER_OUT=>true,
      ];
      }
      else//Method GET
      {
      $curlOptions=[
      CURLOPT_HTTPHEADER=>[
      ‘x-api-key: ‘.$gdxApiKey,
      ‘Authorization: Bearer ‘.$gdxApiKey,
      ],
      CURLOPT_URL=>$curlUrl,
      CURLOPT_CUSTOMREQUEST=>’GET’,
      CURLOPT_RETURNTRANSFER=>true,
      CURLINFO_HEADER_OUT=>true,
      ];
      }
      curl_setopt_array($ch, $curlOptions);
      $response = curl_exec($ch);
      /*—*/
      $arrayInfo=array();
      $arrayInfo[‘header_info’]=curl_getinfo($ch, CURLINFO_HEADER_OUT);
      $arrayInfo[‘response’]=$response;
      var_dump($arrayInfo);
      /*—*/
      //————————————————————————————————
      But the header info always gets set as:
      //—————————————————————————————————————
      ‘header_info’ => string ‘POST /v1/reservations?tripId=XXXXXXXXXXXXXXXXXX&lang=es&verifyDuplicatedReservations=true HTTP/1.1

      Host: stage.ws.gdx.travel

      Accept: */*

      x-api-key: XXXXXXXXXXXXXXXXXXXXXX

      Authorization: Bearer XXXXXXXXXXXXXXXXXXXXXX

      Content-Type​: ​application/json

      Content-Length: 221

      Content-Type: application/x-www-form-urlencoded
      //——————————————————————————————————
      If I remove the CURLOPT_POSTFIELDS option, the headers only gets one “Content-Type” line (application/json, the one that I need)
      Any clues?

      Reply
    5. Luis on October 3, 2019 10:12 am

      it doesn´t work … boolean false is returned, while it works using Postman client

      Reply
    6. Gautam on August 17, 2019 4:57 am

      How to make a get request to the api using cURL

      Reply
    7. Ihab on July 31, 2019 7:21 pm

      curl_setopt($ch, CURLOPT_HTTPHEADER, array(
      ‘Content-Type: application/json’,
      ‘Content-Length: ‘ . strlen($payload))
      );

      You are asking for strlen($payload); which is the string-length while $payload is an array, so that gives an error?

      Any advise?

      Reply
      • Cotton on August 9, 2019 4:13 am

        IHAB,

        json_encode turns the array into a JSON string, so strlen() will work.

        Reply
    8. RAFAEL LUCAS TEODORO DIAS on July 29, 2019 7:53 am

      Thanks a lot

      Reply
    9. Jeffery Triggs on May 31, 2019 6:29 pm

      This was very helpful! Thanks for posting!

      Reply
    10. Dheeraj on May 25, 2019 4:36 am

      Your all tutorilas are awesome bro. Plese provide some a big project in Core Php or CI .

      Reply
    11. Richard on December 13, 2018 9:41 pm

      How about radio buttons or select option?

      Reply

    Leave A Reply Cancel Reply

    Advertisement
    Recent Posts
    • Implementing a Linux Server Security Audit: Best Practices and Tools
    • cp Command in Linux (Copy Files Like a Pro)
    • 15 Practical Examples of dd Command in Linux
    • dd Command in Linux (Syntax, Options and Use Cases)
    • Iptables: Common Firewall Rules and Commands
    Facebook Twitter Instagram Pinterest
    © 2023 Tecadmin.net. All Rights Reserved | Terms  | Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.