AndroidEnthusiast
AndroidEnthusiast

Reputation: 6657

Posting JSON using PHP Curl

I'm trying to post some JSON data in PHP on my local server. I have the following code below but it's not working. Did i miss a vital thing?

    $url = 'http://localhost/mmcv/chart1.php';

    //open connection
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL,$url);        
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json);                                                                  
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                      
    curl_setopt($ch, CURLOPT_HTTPHEADERS,array('Content-Type: application/json'));  


    $result = curl_exec($ch);

Upvotes: 0

Views: 384

Answers (2)

Eugene
Eugene

Reputation: 3375

Maybe your problem is in the receiving script. Try the following in "mmcv/chart1.php":

$rawInput = file_get_contents('php://input');

if(is_string($rawInput)) {
    if(!is_null($jsonInput = json_decode($rawInput, true)))
        $_POST = $jsonInput;
}

Upvotes: 1

rohitarora
rohitarora

Reputation: 1365

curl_setopt($ch, CURLOPT_HTTPHEADERS,array('Content-Type: application/json'));

even if you are posting json you still have to send data in url encoded form so send it like

curl_setopt($ch, CURLOPT_HTTPHEADERS,array('Content-Type: application/x-www-form-urlencoded'));

and use

curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

instead of

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

Upvotes: 1

Related Questions