Login to site with PHP cURL


I’m trying login to a remote site, by having curl to the login form.
I want to redirect to another subdomain and get content.
The code I have doesn’t seem to work and only tries to show the main page of the site.

$username = 'user';
$password = 'pass';
$loginUrl = 'https://site_url';

//init curl
$ch = curl_init();

//Set the URL to work with
curl_setopt($ch, CURLOPT_URL, $loginUrl);

curl_setopt($ch, CURLOPT_POST, 1);

//Set the post parameters
curl_setopt($ch, CURLOPT_POSTFIELDS, 'user='.$username.'&password='.$password);

//Handle cookies for the login
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
 curl_setopt ($ch, CURLOPT_COOKIEFILE, 'cookie.txt');

//Setting CURLOPT_RETURNTRANSFER variable to 1 will force cURL
//not to print out the results of its query.
//Instead, it will return the results as a string return value
//from curl_exec() instead of the usual true/false.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

//execute the request (the login)
$store = curl_exec($ch);

//the login is now done and you can continue to get the
//protected content.

//set the URL to the protected file
curl_setopt($ch, CURLOPT_URL, 'https://site_url/statistics');

//execute the request
$content = curl_exec($ch);


//save the data to disk
file_put_contents('~/file.txt', $content);


Does it have to be via cURL?

Have you considered leveraging a library like Guzzle?
They have good documentation that covers scenarios as you have described.

Something like the below but could be laid out better

use GuzzleHttp\Client;
use GuzzleHttp\Exception\BadResponseException;

$client = new Client(['base_uri' => 'https://url_site/', 'cookies' => true]);

// Login
try {
            'form_params' => [
                'username' => $username,
                'password' => $password,
} catch (BadResponseException $e) {
    echo "Error Logging On for User {$username}";

// Navigate
$response = $client->request('GET', '/statistics');
$content = $response->getBody()->getContents();
file_put_contents('~/file.txt', $content);

Answered By – Nigel

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published