I would like to use a PHP script to call a website using curl and read out data there. The problem is that there is no API for this website. So far, everything works fine, but the website requires authentication and checks if a cookie has been saved. From then on, the PHP script unfortunately does not work anymore. I have no idea how to check the cookie storage, but I have to somehow manage that Curl pretends that the cookie is being stored.
Does any of you have an idea?
$agent = "Mozilla/5.0 Gecko/13.0 Firefox/13.0";
$header[] = "Accept: text/vnd.wap.wml,*.*";
$ch = curl_init($url);
if ($ch)
{
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_COOKIEJAR, "");
curl_setopt($ch, CURLOPT_COOKIEFILE, "");
$postdata = "?username=username&password=password";
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
$tmp = curl_exec ($ch);
curl_close ($ch);
}
return $tmp;
cURL will keep its session cookies until you close or re-initialize the handle, so don't do that and you should be fine. In this example, any cookies you receive from $url
will be passed on to $new_url
.
$agent = "Mozilla/5.0 Gecko/13.0 Firefox/13.0";
$header[] = "Accept: text/vnd.wap.wml,*.*";
$postdata = ["username"=>"username", "password"=>"password"];
$ch = curl_init($url);
if (!$ch) {
echo "ERROR!";
return false;
}
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_USERAGENT => $agent,
CURLOPT_HTTPHEADER => $header,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_COOKIEFILE => "",
CURLOPT_POSTFIELDS => $postdata,
CURLOPT_POST => true,
]);
$tmp = curl_exec($ch);
$curl_setopt_array($ch, [
CURLOPT_URL => $new_url,
CURLOPT_GET => true,
CURLOPT_POSTFIELDS => null,
CURLOPT_POST => false,
]);
$tmp = curl_exec($ch);
curl_close($ch);
return $tmp;
A couple of notes: CURLOPT_POSTFIELDS
is safer passed an array. This way PHP takes care of URL encoding everything for you. CURLOPT_COOKIEFILE
set to an empty string will store cookies in memory, there's no need to specify CURLOPT_COOKIEJAR
. Personal preference, but I find curl_setopt_array()
much easier to use and read.