Curl post username/password to login

2.1k views Asked by At

I would like using Curl (or just any other method) to send login details to a login page. Here's the code I'm using.

<?php
$username='myMAIL/USERNAMEhere'; 
$password='myPASSWORDhere'; 
$postdata = 'username='.$username.'&password='.$password;

// INIT CURL
$ch = curl_init();

// SET URL FOR THE POST FORM LOGIN
curl_setopt($ch, CURLOPT_URL,     'https://secure.runescape.com/m=weblogin/loginform.ws?        mod=www&ssl=1&expired=0&dest=account_settings.ws?jptg=ia&jptv=navbar');

// ENABLE HTTP POST
curl_setopt ($ch, CURLOPT_POST, 1);

// SET POST PARAMETERS : FORM VALUES FOR EACH FIELD
curl_setopt ($ch, CURLOPT_POSTFIELDS, $postdata);

// IMITATE CLASSIC BROWSER'S BEHAVIOUR : HANDLE COOKIES
curl_setopt ($ch, CURLOPT_COOKIEJAR, '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 1st REQUEST (FORM LOGIN)
$store = curl_exec ($ch);

// CLOSE CURL
curl_close ($ch); 

if ($store=='') {

//username and password are valid
//if login is valid, hotfile website returns nothing
echo '<br><i>Login Works!! Enjoy.</i>';

} else {

//username and password are not valid
//if username or password is invalid, the website returns 
//invalid username or password page
echo '<br><i>Login does not work.</i>';

}

?>

But it keeps saying that the login details are wrong while they are not.

Here's a demo with legitimate username/password: http://jaydz.me/test2/

1

There are 1 answers

7
rojoca On

You need:

$postdata = 'username='.$username.'&password='.$password;

EDIT:

In your linked example the form you are trying to replicate with curl includes all parameters as hidden fields, i.e., they all get sent as POST parameters.

$fields = array(
    'username='. urlencode($username),
    'password=' . urlencode($password),
    'mod=www',
    'ssl=1',
    'expired=0',
    'dest=' . urlencode('account_settings.ws?jptg=ia&jptv=navbar')
);
$postdata = implode('&', $fields);

If you can login via a browser to that page you should try using the chrome dev tools to inspect the request. You should be able to see the exact POST data that is sent.

It may be the case that the service you are trying to POST to is rejecting your requests based on something else like the User Agent header. In which case your curl request should try and replicate the browser request as closely as possible. Again, check all the headers being sent in chrome and add these to your curl request.