sa-tasche
1/1/2018 - 2:43 PM

Log in to a website with cURL

Log in to a website with cURL

<?php
#declare(strict_types=1);

function build_unique_path(string $directory) {
    $tempDir = sys_get_temp_dir();
    $directory = trim($directory, '\\/');

    $id = uniqid();
    $uniqDir = "{$directory}.{$id}";
    $tempdir = mkdir($uniqDir);
  
    return $tempdir;
}
<?php
# Source: https://stackoverflow.com/questions/3008817/login-to-remote-site-with-php-curl

//username and password of account
$username = 'MyName';
$password = 'MySecurePasword';

$userAgent = 'Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.7.12) Gecko/20050915 Firefox/1.0.7';
$referer = $_SERVER['REQUEST_URI'];

// set the directory for the cookie
$dir = "cookies/{$username}";
// build a unique path with every request to store 
// the info per user with custom function. 
$path = build_unique_path($dir);
$cookie_file_path = "{$path}/cookie.txt";

// login form action url
$url = 'https://www.example.com/login/action'; 

// grabbing
$maxRedirs = 3; # see CURLOPT_MAXREDIRS
$grabThis = 'http://www.example.com/page/';
$postinfo = "username={$username}&password={$password}";

$curl = curl_init();
$postinfo = curl_escape($curl, $postinfo);
$logInOptions = [
        CURLOPT_COOKIEJAR => $cookie_file_path,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $postinfo,
        CURLOPT_URL => $url,
        CURLOPT_HEADER => false,
        CURLOPT_NOBODY => true,
        CURLOPT_FOLLOWLOCATION => false,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_USERAGENT => $userAgent,
        CURLOPT_REFERER => $referer,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_FORBID_REUSE => false
    ];
curl_setopt_array($options);
curl_exec($curl);

//page with the content I want to grab
$grabOptions = [
        CURLOPT_URL => $grabThis,
        CURLOPT_NOBODY => false,
        CURLOPT_FOLLOWLOCATION => true
        CURLOPT_MAXREDIRS => $maxRedirs,
        CURLOPT_AUTOREFERER => true,
        CURLOPT_FORBID_REUSE => true
    ];
curl_setopt_array($grabOptions + $logInOptions);

if (version_compare(phpversion(), '7.0.7', >=)):
    curl_setopt(CURLOPT_TCP_FASTOPEN, true);
endif;

if (200 == curl_getinfo($curl, CURLINFO_HTTP_CODE)):
    //do stuff with the html
    $html = curl_exec($curl);
else:
    // do stuff with the errors
    print 'Error!'
endif;

curl_close($curl);