Wednesday 13 March 2013

Posting Json data with php curl and then grabbing it ...

Hello Friends

In this blog you will be seeing how can be pots json data using php and then grab it on other page

You will need two scripts for that ..
1. postJson.php
2. handleCurl.php


I am assuming that before reading this post you have priliminary knowledge of php and curl.
                     
                                                 script for postJson.php

This script is to post the json data using php curl.


  • Since we are sending json data we need to tell this to the http header ..for this we are using custom headers and setting it using CURLOPT_HTTPHEADER.
  • Other this to notice is that since we are not using simple post so we are not using CURLOPT_POST instead we are using  CURLOPT_CUSTOMREQUEST ans setting it to "POST".
                   
<?php

#------- initializations(init)-------------

$data = array("param1" => "1234", "param2" => "30051987", "param3" => "myparam");

$data_string = json_encode($data);

$url = 'http://localhost/handleCurl.php';

#----------------(/init)---------------------------



#-----------curl setting(curl)-----------------

$ch = curl_init($url);

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");

curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

curl_setopt($ch, CURLOPT_HTTPHEADER, array(

                     'Content-Type: application/json',

                     'Content-Length: ' . strlen($data_string))

                     );

$result = curl_exec($ch);

curl_close($ch);

#-------------------(/curl)---------------------

echo $result; // this echo is to see what we have received on handleCurl.


?>
                                          script for handleCurl.php
        
<?php
fopen('php://input','r');
 $rawData =stream_get_contents($fp);
 echo "<pre>" print_r($rawData);
 echo "</pre> 
?>";
  • Now some of  you  may ask why  have we used fopen() and stream_get_contents() instead of $_POST..??
  • The reason for thsi is since we are posting json data using customised headers .. $_POST will not be populated...and we have to get the raw input stream fopen()....


 Thats its .....and you  are done.!!!!

Thanks .. meet you with some other post soon.. Have a nice time !!

1 comment: