user3135240
user3135240

Reputation: 11

PHP Curl equivalent of command line curl

I have a working command line curl command

curl -v -d '{"auth": {"passwordCredentials": {"username": "myusername", "password": "mypassword"}}}' -H 'Content-type: application/json' myurl

I am trying to write equivalent PHP curl command -

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, myurl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
$data = array('json' => '{auth: {passwordCredentials : {username : myusername, password : mypassword }}}');
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$output = curl_exec($ch);
echo $output;

I am having different response for both the calls. I have doubt about setting the json data correctly.

Upvotes: 1

Views: 2066

Answers (2)

Sabuj Hassan
Sabuj Hassan

Reputation: 39355

Along with your curl request, also send the HTTP header. For example:

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));

And the post data should be:

$post_data = '{auth: {passwordCredentials : {username : myusername, password : mypassword }}}';
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);

Upvotes: 1

Floris
Floris

Reputation: 46365

You can use the json_encode function to make sure that things are properly encoded.

See for example https://stackoverflow.com/a/4271654/1967396 .

In your case, it might look like this:

$authData = array(auth =>  array(passwordCredentials => array( username => floris, password => secret )));

and then you create the POST data with

curl_setopt($ch, CURLOPT_POSTFIELDS, array('json'=>json_encode($authData)));

If you do

print json_encode($authData);

you get

{"auth":{"passwordCredentials":{"username":"floris","password":"secret"}}}

Presumably you could do this manually, without the json_encode function.

Upvotes: 0

Related Questions