Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reuse php curl response cookie and bypass login steps on the script's subsequent executions?

I have the following php code that logs in to a password protected page and grabs the protected page.The script is working fine but i want to use the login function only once, if i want to grab another protected page within same domain .

i want to use cookie file to open the next protected page instead of using login function again !in another word i just want to bypass the login step for grabbing other protected pages.

Could any one show me how this can be done?

Note: My login function doesnt create any cookies i dont see it in same folder as the script!could any one tell me why?

<?

        $ch=login();
    $html=downloadUrl('http://www.example.com/page1.asp', $ch);

    ////echo $html;


    function downloadUrl($Url, $ch){
        curl_setopt($ch, CURLOPT_URL, $Url);
        curl_setopt($ch, CURLOPT_POST, 0);
        curl_setopt($ch, CURLOPT_REFERER, "http://www.google.com/");
        curl_setopt($ch, CURLOPT_USERAGENT, "MozillaXYZ/1.0");
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        $output = curl_exec($ch);
        return $output;
    }



   function login()
   {
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/login.asp'); //login URL
      curl_setopt ($ch, CURLOPT_POST, 1);
      $post_array = array(  
       'txtUserName'=>'brad',  
       'txtPassword'=>'bradpassword',  
        );
        curl_setopt ($ch, CURLOPT_POSTFIELDS, $post_array);
        curl_setopt ($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
        $store = curl_exec ($ch);
        return $ch;
  } 
?>
<html>


<br>
<textarea rows="30" cols="150"><?PHP  print_r($html); ?></textarea>
</html>
like image 898
user1788736 Avatar asked Jun 01 '13 17:06

user1788736


1 Answers

Use

curl_setopt($ch,CURLOPT_COOKIEJAR, $cookieFileLocation);
curl_setopt($ch,CURLOPT_COOKIEFILE, $cookieFileLocation);

In second request where $cookieFileLocation is the location of your cookie file.

You have to have 2 requests. First is login request which fills the cookie file.

You have to check if your cookie file exists is_file($cookieFileLocation), and if it does you can perform second request for download protected content bypassing the login process.

You should note that most of the systems has session expire time, so you have to make login after period of time. I would check html of returned page for login error as mark that i have to login again.

like image 114
bksi Avatar answered Oct 12 '22 23:10

bksi