0

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);
9
  • did you enable curl first of all in your server? Commented Feb 14, 2013 at 14:15
  • check whether curl is enabled or not using this code in your server if (!function_exists('curl_init')) { throw new Exception('PHP cURL extension is not present.'); } Commented Feb 14, 2013 at 14:17
  • @Venkat I'm not quite sure if i have. I used curl to fetch data from an API previously, does this still mean i would have to enable it on my end? Commented Feb 14, 2013 at 14:18
  • check once what is wrong in checking just do this if you are using Xampp go to htdocs folder create a test.php file paste the above code and run it.If you get any error post it here... Commented Feb 14, 2013 at 14:20
  • @Venkat it doesn't work i just get a server error : "HTTP Error 500 (Internal Server Error): An unexpected condition was encountered while the server was attempting to fulfill the request." Commented Feb 14, 2013 at 14:25

2 Answers 2

1

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

thanks this definitely helped! it was a problem with a line in my code
1
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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.