•  0
    PHP

    How to POST json data and Receive post input data using Curl PHP

      Admin     3465        0        Report content

    Sometimes we need to use other method to post and receive data. In php, cURL is one of the option that we can used.

    In this example, we gonna POST data using cURL in json format as shown below:

           $data_string = json_encode(array('data1'=>'value1','data2'=>'value2'));
        $url = "http://example.com/curl.php";
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        $arrHeaders = array(
            'Accept:application/json',
            'Content-Length:'.strlen($data_string)
        );
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $arrHeaders);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
        $result = curl_exec($curl);
        curl_close($curl);

    To receive the POST input data, we need to use file_get_contents and json_decode as shown below:

        $data = json_decode(file_get_contents('php://input'), true);

        $data1 = $data['data1'];

        $data2 = $data['data2'];

     


  •  


Leave a Comment

Please Login to insert comment.

 

Facebook Conversations