开发者

using curl and storing cookie as a variable

开发者 https://www.devze.com 2023-03-18 23:32 出处:网络
i have a curl function that visits a website, logs in to said website, stores the cookie file, then can later read the cookie file to visit a page that would normally require a login.

i have a curl function that visits a website, logs in to said website, stores the cookie file, then can later read the cookie file to visit a page that would normally require a login.

problem i am faced with is i want to save and retrieve the cookie file using a php variable but cant seem to get it to work.

$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;
}

i assume the syntax is wrong, and not that curl cant handle a variable as a location?


The problem is the scope of the $username variable. Because it's outside the function, it's not available inside the function. You should either add the username as a parameter of the function or use the global keyword so that it's accessible inside the function.

See http://ca2.php.net/manual/en/language.variables.scope.php for more information.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号