Facebook Twitter Instagram
    TecAdmin
    • Home
    • Ubuntu 20.04
      • Upgrade Ubuntu
      • Install Java
      • Install Node.js
      • Install Docker
      • Install LAMP Stack
    • Tutorials
      • AWS
      • Shell Scripting
      • Docker
      • Git
      • MongoDB
    • FeedBack
    • Submit Article
    • About Us
    Facebook Twitter Instagram
    TecAdmin
    Home»Programming»PHP»How To POST JSON Data with PHP cURL

    How To POST JSON Data with PHP cURL

    RahulBy RahulMarch 9, 20181 Min ReadUpdated:March 28, 2019

    The PHP cURL is a library used for making HTTP requests. In order to use PHP cURL, you must have installed and enabled libcurl module for PHP on your system. In this tutorial, you will learn how to POST JSON data with PHP cURL requests. Basically, there are 4 steps involved to complete a cURL request using PHP.

    • curl_init — The first step is to initializes a new session of cURL and return a cURL handle to other functions.
    • curl_setopt — The second step is to set options for a cURL session handle. All these settings are very well explained at curl_setopt().
    • curl_exec — In third step it perform a cURL session based on above options set.
    • curl_close — The last step is to close a cURL session initialize by curl_init() and free all resources. Also deleted the cURL handle.

    Let’s use the below sample code to create a POST request with PHP cURL.

    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
    30
    31
    <?php
    // A sample PHP Script to POST data using cURL
    // Data in JSON format
     
    $data = array(
        'username' => 'tecadmin',
        'password' => '012345678'
    );
     
    $payload = json_encode($data);
     
    // Prepare new cURL resource
    $ch = curl_init('https://api.example.com/api/1.0/user/login');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLINFO_HEADER_OUT, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
     
    // Set HTTP Header for POST request
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Content-Length: ' . strlen($payload))
    );
     
    // Submit the POST request
    $result = curl_exec($ch);
     
    // Close cURL session handle
    curl_close($ch);
     
    ?>

    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.

    curl libcurl PHP
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email WhatsApp
    Previous ArticleHow To Install VirtualBox Guest Additions on Fedora 29-25, CentOS 7/6
    Next Article How to Install s3cmd in Linux and Manage S3 Buckets

    Related Posts

    How to Install Composer on Ubuntu 22.04

    Updated:June 24, 20223 Mins Read

    How To Install PHP (8.1, 7.4 or 5.6) on Ubuntu 22.04

    Updated:June 19, 20223 Mins Read

    How To Install Linux, Nginx, MySQL, & PHP (LEMP Stack) on Ubuntu 22.04

    Updated:April 7, 20227 Mins Read

    How to Install Apache, MySQL, PHP (LAMP Stack) on Ubuntu 22.04

    Updated:June 28, 20225 Mins Read

    How To Setup Apache, PHP & MongoDB in Ubuntu & Debian

    Updated:October 8, 20213 Mins Read

    How To Install and Use PHP Composer on Debian 11

    Updated:February 16, 20224 Mins Read

    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

    Recent Posts
    • What is CPU? – Definition, Types and Parts
    • What is the /etc/aliases file
    • What is the /etc/nsswitch.conf file in Linux
    • How to Install Ionic Framework on Ubuntu 22.04
    • What is the /etc/hosts file in Linux
    Facebook Twitter Instagram Pinterest
    © 2022 Tecadmin.net. All Rights Reserved | Terms  | Privacy Policy

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