If I go to a website, example.com/page1.php, it is a log-in page. When I log-in, it takes me to example.com/page2.php. If I close my browser and come back to page1 later, I’m still logged in and it automatically takes me to page2. That means there’s a cookie set and it knows I already logged in.
I want to use file_get_contents
to get page2.php. When I try it, I get the contents of the log-in page instead. I assume that’s because file_get_contents
doesn’t know a cookie is set and page2 is saying, you shouldn’t be here, you’re not logged in, so it bumps me back to page 1.
I realize I can use cURL to do the log-in, create a cookie and get the contents, like this….
$url = 'https://www.example.com/page1.php'; // the url of the login page
$post_data = "urerid=myusername&password=mypassword "; // The login data to post
$ch = curl_init(); // Create a curl object
curl_setopt($ch, CURLOPT_URL, $url ); // Set the URL
curl_setopt($ch, CURLOPT_POST, 1 ); // This is a POST query
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); //Set the post data
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Get the content
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // Follow Location redirects
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt'); // Set cookie storing files
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt');
$output = curl_exec($ch); // Execute the action to login
My problem is , I don’t want to log-in again (for reasons I don’t want to get into). Is there a way to let file_get_contents
, cURL, or some other function, know I’m previously logged in and get the contents of page2. Since example.com is setting a cookie, can I access that cookie somehow and use it to avoid logging in again?