0

Please don't close this question before read my actual problem. I have seen many related problems but I am still having. Simply I want to send a json_encoded array by POST method using CURL in PHP. When I set content-type as application/json the data is not posted. I receive empty post array. When I remove content-type line the data is posted but not as json. Here is my code

 $data = array('id' => $post['id'], 'action' => $post['action']);
 $post_data = http_build_query($data);
 curl_setopt($ch, CURLOPT_URL, $url);
 curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
 curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
 curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_data));

I this case I receive empty post. If I comment out the line curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); I will receive the post data but not json encoded. I want json_encoded array. Will any one tell me what am I doing wrong?

Best Regards:

2
  • Are you certain the target resource allows you to request the response format? Commented Dec 8, 2012 at 18:36
  • I am sending request to my other controller. How can I come to know that target resource allows or not? Commented Dec 8, 2012 at 18:39

2 Answers 2

1

You are encoding a query string to json not an array remove $post_data = http_build_query($data); and pass $data to json_encode.

 $data = array('id' => $post['id'], 'action' => $post['action']);
 curl_setopt($ch, CURLOPT_URL, $url);
 curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
 curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
 curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

ofcourse for this to work the service nedds to support json posts.

Sign up to request clarification or add additional context in comments.

4 Comments

When I remove http_build_query($data), even then request is not posted. Empty post
What is meant by the service nedds to support json posts.? How can I come to know whether the supports or not?
@AwaisQarni use json_decode(file_get_contents("php://input"), true) to get the posted data.
If I want to check whether the posted data is json encoded or not? I am checking if (is_object(json_decode($post))) but now how can I?
1

Try send-n-accept RAW POST request, via

<?php $postdata = file_get_contents("php://input"); ?> 

RAW POST

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.