使用curl并将cookie存储为变量

时间:2011-07-10 07:03:12

标签: php variables curl

我有一个curl函数访问网站,登录到所述网站,存储cookie文件,然后可以读取cookie文件以访问通常需要登录的页面。

我面临的问题是我想使用php变量保存和检索cookie文件,但似乎无法使其工作。

$username = "myusername";
function getUrl($url, $method='', $vars='') {
$ch = curl_init();
if ($method == 'post') {
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);
}
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_COOKIEJAR, "cookies/$username.txt");
curl_setopt($ch, CURLOPT_COOKIEFILE, "cookies/$username.txt");
$buffer = curl_exec($ch);
curl_close($ch);
return $buffer;
}

我假设语法错误,而不是卷曲不能将变量作为位置处理?

1 个答案:

答案 0 :(得分:1)

问题是$username变量的范围。因为它在函数之外,所以在函数内部不可用。您应该将用户名添加为函数的参数,或使用global关键字,以便可以在函数内访问它。

有关详细信息,请参阅http://ca2.php.net/manual/en/language.variables.scope.php