简体   繁体   中英

Why is the curl code not executed in PHP script? (WAMP Server)

I am trying to get a token to use the Microsoft Graph API ( https://docs.microsoft.com/en-us/graph/auth-v2-user?context=graph%2Fapi%2F1.0&view=graph-rest-1.0 ) via Curl. I have set up a simple Php file with this function:

function getToken() {
echo "start gettoken";
var_dump(extension_loaded('curl'));
$jsonStr = http_build_query(Array(
    "client_id" => "***",
    "scope" => "https://graph.microsoft.com/.default",
    "client_secret" => "***",
    "grant_type" => "client_credentials"
));
$headers = Array("Content-Type: application/x-www-form-urlencoded", "Content-Length: " . strlen($jsonStr));

$ch = curl_init("https://login.microsoftonline.com/***.onmicrosoft.com/oauth2/v2.0/token");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$token = curl_exec($ch);
echo "test after curl";

return $token;

curl_error($ch);

 }

However, what I want to know is why the curl request is not working. Also the echo after the curl codeblock is not being executed, while 'start gettoken' is. PHP_curl is enabled in my WAMP. Why is this?

Are you sure CURL is enabled because that code you have posted is ok and giving echo response before and after curl execution.

you're sending the token request in a JSON-format, and then you're lying to the server saying it's application/x-www-form-urlencoded -encoded when it's actually application/json -encoded, since these 2 formats are completely incompatible, the server fails to parse it. and... ideally it should have responded HTTP 400 bad request (because your request can't be parsed as x-www-form-urlencoded)

anyhow, to actually send it in the application/x-www-form-urlencoded -format, replace json_encode() with http_build_query()

also get rid of the "Content-Length:" -header, it's easy to mess up (aka error-prone) if you're doing it manually (and indeed, you messed it up! there's supposed to be a space between the : and the number, you didn't add the space, but the usual error is supplying the wrong length), but if you don't do it manually, then curl will create the header for you automatically, which is not error-prone.

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