I’m trying to log into a forum using cURL and save the cookie to a file, then parse the cookie to get the phpbb2mysql_sid cookie. Here’s my code thus far:
<?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;
However, I’m getting this error when I run the script:
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
If I check my filesystem the file is there. And the code to get the file contents is after the cURL request, so the file should exist, right?
Found the problem. The cookie file is only saved once
curl_close()is called. Simply close the cURL handle before thefile_get_contents()call and it works like a charm.