如何在php curl中的GET请求中传递令牌参数?

时间:2019-09-28 14:53:05

标签: php access-token php-curl

在Laravel 5.8应用程序中,我将API与方法描述结合使用:

curl --location --request GET "/api/user" \
   --header "Accept: application/json" \
   --header "Authorization: Bearer <user access token>"

但是我无法在php curl中的GET请求中传递令牌参数吗?

我试图做

$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);

我收到了消息:

  

重定向到http://myserver.com/login

与url类似的问题:

curl_setopt($ch, CURLOPT_URL, $this->admindashApi . '/api/user?token=' . $logged_user_token);

我尝试过:

curl_setopt($ch, CURLOPT_URL, $this->admindashApi . '/api/user?Authorization=' . 'Bearer '. $logged_user_token);

但是出现错误:

<!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>

是否必须将其放入CURLOPT_HTTPHEADER中? 我怎样才能做到这一点? 哪种方法有效?

1 个答案:

答案 0 :(得分:2)

很正确,您必须将标题添加到CURLOPT_HTTPHEADER

这可以通过将您设置为CURLOPT_HTTPHEADER的PHP数组对象中添加。

$headers = array(
    "Content-Type: application/json; charset=utf-8",
    "Authorization: Bearer ".$logged_user_token
);

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

在这里,您将使用 both $headersAuthorization标头创建php数组对象Content-Type。然后,您将CURLOPT_HTTPHEADER设置为使用该标题数组。