PHP Posts

How to Simulate JSon POST Request Using PHP and CURL

Basically, im trying to do a PHP POST request using JSon string as its format and able to consume JSon array string as responses. Dont forget to activate CURL in your php.ini file.


//set POST variables address and json string
$url = 'http://localhost:81/dudu.php';
$fields = array(

//url-ify the data for the JSON POST
$fields_string = json_encode($fields);

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_RETURNTRANSFER , 1);

//execute post
$jsonResult = curl_exec($ch);

//close connection

// [{"name":0,"email":""},{"name":1,"email":""},
// {"name":2,"email":""},{"name":3,"email":""}]
$results = json_decode($jsonResult, true);
foreach ( $results as $result )
    echo "name : {$result['name']} and email {$result['email']} <br />";


This is what my browser will look like after im testing my JSon POST

Have fun with CURL :-)


How to Handle JSon POST Request Using PHP

On my last project, i need to create a php service using JSon to handle service requests from multiple clients. My PHP file would consume JSon string for its requests and produce JSon string as its responses.
Im not too familiar with PHP, but after sometime googling i’ve found a workaround. This is how i do it.

// JSon request format is : 
// {"userName":"","password":"12345","emailProvider":"zzzz"}

// read JSon input
$data_back = json_decode(file_get_contents('php://input'));

// set json string to php variables
$userName = $data_back->{"userName"};
$password = $data_back->{"password"};
$emailProvider = $data_back->{"emailProvider"};

// create json response
$responses = array();
for ($i = 0; $i < 10; $i++) {
    $responses[] = array("name" => $i, "email" => $userName . " " . $password . " " . $emailProvider);

// JSon response format is : 
// [{"name":"eeee","email":""},
// {"name":"aaaa","email":""},{"name":"cccc","email":""}]

// set header as json
header("Content-type: application/json");

// send response
echo json_encode($responses);

This is the http header and body of request and response.

Hope it help others, have fun with JSon. ;-)