命令行cURL到PHP cURL


command line cURL to PHP cURL

curl -H 'content-type: application/json' --insecure -d '{"client_id":"w44p0d00.apps.2do2go", "client_secret":"mvlldlsfKLLSczxc12Kcks910cccs", "grant_type":"client_credentials", "scope": "anonymous"}' https://someurl.com/oauth/token

这个命令行cURL工作得很好。如何在PHP中实现相同的功能?

curl_setopt($ch, CURLOPT_URL, 'https://someurl.com/oauth/token'); //this my url
curl_setopt($ch, CURLOPT_HTTPHEADER, array('content-type: application/json')); //its -H
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

这相当于您的--insecure参数:

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

它相当于你的-d参数在你张贴json对象。

$json = '{"client_id":"w44p0d00.apps.2do2go", "client_secret":"mvlldlsfKLLSczxc12Kcks910cccs", "grant_type":"client_credentials", "scope": "anonymous"}';
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);

将这些内容添加到现有的curl中后,执行以下操作来执行curl并打印数据:

$response = curl_exec($ch);
curl_close($ch);
print $response;
$url = 'https://someurl.com/oauth/token';
$fields = array(
    'client_id' => urlencode("w44p0d00.apps.2do2go"),
     ....
);

foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('content-type: application/json'));
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);