在PHP Curl Serverside中获取和设置Cookie

时间:2018-04-11 14:21:02

标签: php curl oauth php-curl

在登录API期间,我通过CURL接收一些服务器设置。我有以下脚本提取收到的Cookie。我需要以下的Curl调用来发送第一次调用时收到的cookie - 不知怎的,我无法让它工作:

<?php 
$ch = curl_init('https://www.test.com/getcookie');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
$result = curl_exec($ch);
preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $result, $matches);
$cookies = array();
foreach($matches[1] as $item) {
parse_str($item, $cookie);
$cookies = array_merge($cookies, $cookie); }

var_dump($cookies);
?>

在此之后我想调用另一个API服务并发送刚刚收到的cookie,但这不起作用?

<?php

$curl = curl_init( 'https://test.com/api' );
curl_setopt( $curl, CURLOPT_HTTPHEADER, array( 'Authorization: Bearer ' . $token ) );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt( $curl, CURLOPT_COOKIEFILE, $cookies);
$getbalance = curl_exec( $curl );
curl_close($curl);
?>

1 个答案:

答案 0 :(得分:0)

Curl自主管理cookie,您无需解析和设置它们:

<?php 
$ch = curl_init('https://www.test.com/getcookie');

$cookiesFile = "cookies.txt"; // <--- cookies are stored here

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, false); // <---

curl_setopt($ch, CURLOPT_COOKIEFILE, $cookiesFile ); // <---
curl_setopt($ch, CURLOPT_COOKIEJAR,  $cookiesFile ); // <---

$result = curl_exec($ch);

curl_close($ch);

if( $result === false ) {
    // failure
}

然后

<?php

$cookiesFile = "cookies.txt"; // <--- cookies are retrieved here

$curl = curl_init( 'https://test.com/api' );
curl_setopt( $curl, CURLOPT_HTTPHEADER, array( 'Authorization: Bearer ' . $token ) );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1);

curl_setopt( $curl, CURLOPT_COOKIEFILE, $cookiesFile ); // <---
curl_setopt( $curl, CURLOPT_COOKIEJAR,  $cookiesFile ); // <---

$getbalance = curl_exec( $curl );
curl_close($curl);

您可以指定curl存储和读取cookie的文件,如上例所示。

随后的curl调用会更新cookie文件。

首次调用之前,cookie文件不需要存在,但PHP当然必须具有读/写访问权限。