I found a way to maintain session using a curl call.
Below is a function I found on the web.
I modified the function to handle session and basic authentication.
//See Updates and explanation at: https://github.com/tazotodua/useful-php-scripts/
function get_remote_data($url, $post_paramtrs=false)
{
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
$useragent = $_SERVER['HTTP_USER_AGENT'];
$strCookie = 'PHPSESSID=' . $_COOKIE['PHPSESSID'] . '; path=/';
session_write_close();
$c = curl_init();
curl_setopt($c, CURLOPT_URL, $url);
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
if($post_paramtrs)
{
curl_setopt($c, CURLOPT_POST,TRUE);
curl_setopt($c, CURLOPT_POSTFIELDS, "var1=bla&".$post_paramtrs );
}
curl_setopt($c, CURLOPT_SSL_VERIFYHOST,false);
curl_setopt($c, CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($c,CURLOPT_USERAGENT, $useragent);
curl_setopt( $c, CURLOPT_COOKIE, $strCookie );
curl_setopt($c, CURLOPT_MAXREDIRS, 10);
$follow_allowed= ( ini_get('open_basedir') || ini_get('safe_mode')) ? false:true;
if ($follow_allowed)
{
curl_setopt($c, CURLOPT_FOLLOWLOCATION, 1);
}
curl_setopt($c, CURLOPT_CONNECTTIMEOUT, 9);
curl_setopt($c, CURLOPT_REFERER, $url);
curl_setopt($c, CURLOPT_TIMEOUT, 60);
curl_setopt($c, CURLOPT_AUTOREFERER, true);
curl_setopt($c, CURLOPT_ENCODING, 'gzip,deflate');
//Optional authentication
$username='test';
$password='12345';
curl_setopt($c, CURLOPT_USERPWD, "$username:$password");
curl_setopt($c, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
$data=curl_exec($c);
$status=curl_getinfo($c);
curl_close($c);
preg_match('/(http(|s)):\/\/(.*?)\/(.*\/|)/si', $status['url'],$link); $data=preg_replace('/(src|href|action)=(\'|\")((?!(http|https|javascript:|\/\/|\/)).*?)(\'|\")/si','$1=$2'.$link[0].'$3$4$5', $data); $data=preg_replace('/(src|href|action)=(\'|\")((?!(http|https|javascript:|\/\/)).*?)(\'|\")/si','$1=$2'.$link[1].'://'.$link[3].'$3$4$5', $data);
if($status['http_code']==200)
{
return $data;
}
elseif($status['http_code']==301 || $status['http_code']==302)
{
if (!$follow_allowed)
{
if (!empty($status['redirect_url']))
{
$redirURL=$status['redirect_url'];
}
else
{
preg_match('/href\=\"(.*?)\"/si',$data,$m);
if (!empty($m[1]))
{
$redirURL=$m[1];
}
}
if(!empty($redirURL))
{
return call_user_func( __FUNCTION__, $redirURL, $post_paramtrs);
}
}
}
return "ERRORCODE22 with $url!!<br/>Last status codes<b/>:".json_encode($status)."<br/><br/>Last data got<br/>:$data";
}
You get the html content by using one of these calls:
GET request:
$html = get_remote_data('http://example.com?var1=something'); // GET request
POST request:
$html = get_remote_data('http://example.com', "var2=something&var3=blabla" ); // POST request