【问题标题】:PHP can't find cookie file after cURL requestcURL请求后PHP找不到cookie文件
【发布时间】:2012-08-19 08:15:21
【问题描述】:

我正在尝试使用 cURL 登录论坛并将 cookie 保存到文件中,然后解析 cookie 以获取 phpbb2mysql_sid cookie。到目前为止,这是我的代码:

<?php

$curl = curl_init();

$cookieFile = 'C:\xampp\htdocs\cookies\\' . uniqid(true);

// Login
curl_setopt($curl, CURLOPT_URL, 'http://localhost/phpbb2/login.php');
curl_setopt($curl, CURLOPT_COOKIEJAR, $cookieFile);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($curl, CURLOPT_POST, true);
$postVars = array('username' => 'username', 'password' => 'testing', 'autologin' => 'on', 'login' => 'Log in');
curl_setopt($curl, CURLOPT_POSTFIELDS, $postVars);
$resp = curl_exec($curl);

// Parse sid from cookie file
preg_match('/phpbb2mysql_sid\t(.*)/', file_get_contents($cookieFile), $match);
$sId = $match[1];

echo $sId;

但是,我在运行脚本时遇到了这个错误:

Warning: file_get_contents(C:\xampp\htdocs\cookies\150367764c4ef3) [function.file-get-contents]: failed to open stream: No such file or directory in C:\xampp\htdocs\leech\post.php on line 18

Notice: Undefined offset: 1 in C:\xampp\htdocs\post.php on line 19

如果我检查我的文件系统,文件就在那里。而获取文件内容的代码是 cURL请求之后,所以文件应该存在吧?

【问题讨论】:

  • 你试过curl_setopt($curl, CURLOPT_COOKIEJAR, "path\to\cookiejar.txt"); 吗?另外,echo getcwd(); 输出什么?
  • $cookieFile = 'C:\\xampp\\htdocs\\cookies\\' . uniqid(true);

标签: php cookies curl file-get-contents


【解决方案1】:

发现问题。 cookie 文件仅在调用 curl_close() 时保存。只需在 file_get_contents() 调用之前关闭 cURL 句柄,它就会像魅力一样工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-13
    • 2014-12-09
    • 2015-09-10
    • 1970-01-01
    • 2015-06-24
    • 2014-10-27
    • 2013-06-18
    • 1970-01-01
    相关资源
    最近更新 更多