Search code examples
phpcurlurlencodeurl-encoding

URL Encode With Curl PHP


I made the change suggested and am still receiving a similar error:

{"error":"invalid_request","error_description":"invalid grant type"}

This error is likely to happen if the url-encoding is not set properly. The updated code is below Any help would be greatly appreciated!

<?php

$client_id = '...';
$redirect_uri = 'http://website.com/foursquare2.php';
$client_secret = '...';
$code = $_REQUEST['code'];

$ch = curl_init();

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_URL, "https://id.shoeboxed.com/oauth/token");
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'grant_type' => 'authorization_code',
'code' => $code,
'client_id' => $client_id,
'client_secret' => $client_secret,
'redirect_uri' => $redirect_uri
));

$response = curl_exec($ch);

$err = curl_error($ch);
curl_close($ch);
if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}
?>

Solution

  • your code is sending the data in multipart/form-data format. when you give CURLOPT_POST an array, curl will automatically encode the data in that array in the multipart/form-data format. then you tell the server, with your header, that this data is in application/x-www-form-urlencoded format, and the server will try to parse it as such, and fail, thus your received error.

    first off, get rid of curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded')); altogether. if you're using application/x-www-form-urlencoded, php/curl will automatically add that header for you, and unlike you, php/curl won't make any typos (the devs got automated test suits to make sure this stuff is correct before every release), likewise, if you're using multipart/form-data format, php/curl will add that header for you, so don't add those 2 specific headers manually.

    if you want to use the multipart/form-data format, just get rid of the header saying otherwise. but if you want to use application/x-www-form-urlencoded format, PHP has a built-in function to encode to this format, called http_build_query, so do

    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array(
    'grant_type' => 'authorization_code',
    'code' => $code,
    'client_id' => $client_id,
    'client_secret' => $client_secret,
    'redirect_uri' => $redirect_uri
    )));
    

    (and also get rid of the content-type header, it will be added automatically.)