我有一个curl函数,它访问一个网站,登录到该网站,存储cookie文件,然后可以稍后读取cookie文件访问通常需要登录的页面。
问题我面临的是我想保存和检索cookie文件使用PHP变量,但似乎不能让它工作。
$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;
}
我假设语法是错误的,而不是curl不能处理一个变量作为一个位置?
问题在于$username
变量的作用域。因为它在函数外,所以在函数内不可用。您应该添加用户名作为函数的参数,或者使用global
关键字,以便在函数内部访问它。