简体   繁体   中英

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.

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);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM