卷曲:重定向时保留cookie

时间:2016-02-08 22:00:00

标签: php curl cookies

我使用此代码(最初找到login into webpage with php with cURL)首先获取csrf令牌,创建cookie,然后在后续帖子请求中使用该csrf令牌和cookie。它不起作用(从最终网页看起来如何推断)并且我认为它是因为FOLLOWLOCATION设置为true。它必须设置为true,因为有一些重定向正在进行,但重定向也会带来"错位"饼干。问题是如何在重定向到服务器的响应时保持cookie。

colnames(f)[grep("^V[0-9]*$",names(f))] <- f[1,c(grep("^V[0-9]*$", names(f)))]

/////// HEADER OUT AND IN DATA

 $cookie = 'cookies2.txt';

# Initialize a cURL session.
$ch = curl_init('https://example.com/login');

# Set the cURL options.
$options = [
    CURLOPT_COOKIEJAR       => $cookie,
    CURLOPT_RETURNTRANSFER  => 1,
    CURLOPT_USERAGENT => $useragent,
    CURLOPT_COOKIESESSION => true,
    CURLINFO_HEADER_OUT => true,
    CURLOPT_HEADER=>1

];

# Set the options
curl_setopt_array($ch, $options);

# Execute
$html = curl_exec($ch);

$request = curl_getinfo($ch, CURLINFO_HEADER_OUT);
echo "1.Request sent: $request<br>";

$headerSizeFirst = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$headersFirst = substr($html, 0, $headerSizeFirst);
echo "1.Request recieved: $headersFirst";

$dom = pQuery::parseStr($html);
$csrfToken = $dom->query('[name="csrf"]')->val();

 $postData = [
    'csrf'       => $csrfToken,
     'username'       => $email,
     'password'      => $password
             ...........

 ];


 # Convert the post data array to URL encoded string
 $postDataStr = http_build_query($postData);

 $options[CURLOPT_POST] = 1;
 $options[CURLOPT_POSTFIELDS] = $postDataStr;
 $options[CURLOPT_HEADER]=1;
 $options[CURLOPT_COOKIEJAR]=$cookie;

 $options[CURLOPT_FOLLOWLOCATION] = true;
 $options[CURLOPT_RETURNTRANSFER] = true;
 $options[CURLOPT_USERAGENT] = $useragent;
 $options[CURLINFO_HEADER_OUT] => true,



 curl_setopt_array($ch, $options);

 # Execute
 $response = curl_exec($ch);

$request = curl_getinfo($ch, CURLINFO_HEADER_OUT);
echo "2. Request sent: $request<br>";

$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$headers = substr($response, 0, $headerSize);
echo "2. Request recieved: $headers<br>";
echo $response;

1 个答案:

答案 0 :(得分:1)

CURLOPT_COOKIESESSION设置为true表示您告诉libcurl将其视为(cookie)会话,它将在请求开始时丢弃所有会话cookie。您可能不应该设置它而不确定您需要什么,因为它将刷新所有cookie而没有特定的到期日期/时间。

否则,当在libcurl中激活cookie引擎时,它将保留与句柄相关联的cookie,并在后续使用相同句柄的请求中重用它们。