cutecat654 cutecat654 - 1 month ago 8x
PHP Question

Login and Logout in curl?

I login to my account with this code.';

$postVars = 'username=myuser&password=1234';
$tmpfname = 'cookie.txt';
$page = '/login.php';
$headers = array(
"POST ".$page." HTTP/1.1",
"Content-Type: application/x-www-form-urlencoded; charset=UTF-8",
"Accept: */*",
"Accept-Language: en-US,en;q=0.5",
"Cache-Control: no-cache",
"Content-length: ".strlen($postVars),
"Pragma: no-cache",
"Connection: keep-alive",
"X-Requested-With: XMLHttpRequest",
"Cache-Control: no-cache"

$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postVars);
curl_setopt($ch, CURLOPT_COOKIEJAR, $tmpfname);
curl_setopt($ch, CURLOPT_COOKIEFILE, $tmpfname);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$run = curl_exec($ch);
$info = curl_getinfo($ch);



After Login,I want to visit and,and Logout by visiting

What should I do? Do you have an example?


I guess you want to maintain a session in CURL(just like browser). so that you can visit other pages where access control is activated.

For this what you can do is, save the cookies in a file , while login. and use that cookies while visiting other pages. because generally session are generally maintained via cookies.

If you use CURLOPT_COOKIE_FILE and CURLOPT_COOKIE_JAR then curl will read/write the cookies from/to a file.

So add these 3 lines to all the curl queries.

$ckfile = tempnam ("/tmp", 'cookiename');
curl_setopt ($ch, CURLOPT_COOKIEJAR, $ckfile);
curl_setopt ($ch, CURLOPT_COOKIEFILE, $ckfile);