1

It works fine when I execute it in command line:

$ curl -H "Authorization: Bearer XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"  "https://api.twitter.com/labs/2/users/by?usernames=hikaru__1201&user.fields=created_at"

Result:

{"data":[{"created_at":"2016-09-28T07:02:32.000Z","id":"781026287825645573","name":"ろぐあうと","username":"hikaru__1201"}]}

But it doesn't work in php:

$url = "https://api.twitter.com/labs/2/users/by?usernames=hikaru__1201&user.fields=created_at";
$authorization = 'Authorization: Bearer XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"';

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json' , $authorization ));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$result = curl_exec($ch);
curl_close($ch);
var_dump(json_decode($result)); die();

Result:

class stdClass#1 (4) {
  public $title =>
  string(12) "Unauthorized"
  public $type =>
  string(11) "about:blank"
  public $status =>
  int(401)
  public $detail =>
  string(12) "Unauthorized"
}

exec does work too:

$command = 'curl -H "Authorization: Bearer xxxxxxxxxxxxxxx"  "https://api.
twitter.com/labs/2/users/by?usernames=hikaru__1201&user.fields=created_at"';

exec("$command 2>&1", $output);
var_dump($output); die();

Result:

 ...
       [3] =>
        string(129) "{"data":[{"created_at":"2016-09-28T07:02:32.000Z","id":"781026287825645573","name":"ろぐあうと","username":"hikaru__1201"}]}"

I tried answers from this post https://stackoverflow.com/questions/30426047/correct-way-to-set-bearer-token-with-curl but no luck

whitesiroi
  • 2,725
  • 4
  • 30
  • 64

1 Answers1

2

There is an extra double quote remains at the end of your token.

$authorization = 'Authorization: Bearer XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"';
                                                                               ^>

You can run the curl with verbose enabled (curl_setopt($ch, CURLOPT_VERBOSE, 1);) and it would show you the request it sends to the server.

Example request header which you can see for debug purpose.

> GET / HTTP/1.1
Host: test.com
Accept: */*
Content-Type: application/json
Authorization: Bearer XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" <--extra quote
Sabuj Hassan
  • 38,281
  • 14
  • 75
  • 85