Reputation: 3115
In my Laravel 5.8 app, I use API with method description :
curl --location --request GET "/api/user" \
--header "Accept: application/json" \
--header "Authorization: Bearer <user access token>"
But I failed how to pass token parameter in GET request in php curl?
I tried to do
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $this->serverApiHosting . '/api/user');
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json; charset=utf-8"));
$resp = curl_exec($ch);
$respArray = json_decode($resp);
I received the message:
Redirecting to http://myserver.com/login.
Similar problem with url :
curl_setopt($ch, CURLOPT_URL, $this->admindashApi . '/api/user?token=' . $logged_user_token);
I tried like :
curl_setopt($ch, CURLOPT_URL, $this->admindashApi . '/api/user?Authorization=' . 'Bearer '. $logged_user_token);
But got error :
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>400 Bad Request</title>
</head><body>
<h1>Bad Request</h1>
<p>Your browser sent a request that this server could not understand.<br />
</p>
<hr>
<address>Apache/2.4.10 (Debian) Server at phpstack-NNN-NNNN.cloudwaysapps.com Port 80</address>
</body></html>
</pre>
Do I have to put it in CURLOPT_HTTPHEADER
?
How can I do this?
Which is the valid way?
Upvotes: 1
Views: 6190
Reputation: 1767
You're right that you have to add your header to CURLOPT_HTTPHEADER
.
This can be done by adding to the PHP array object you're setting to CURLOPT_HTTPHEADER
.
$headers = array(
"Content-Type: application/json; charset=utf-8",
"Authorization: Bearer ".$logged_user_token
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
Here, you will be creating the php Array object $headers
with both the Authorization
and Content-Type
headers. You then set your CURLOPT_HTTPHEADER
to use that array of headers.
Upvotes: 2