14 May, 2010

Login to Gmail with curl

Following code is used to login to gmail using curl. The code is quite simple, for curl options please check php manual.
After loging in to gmail with curl provided below, user can then get their contact list of calendar. Only the logging in step is given
in this code. If the gmail login is successfull, then a unique auth key is obtained and if login fails then nothing is returned.

//store username and password and some values in array
$clientPost = array(
"accountType" => "HOSTED_OR_GOOGLE",
"Email" => "gmailusername",
"Passwd" => "gmailpassword",
"service" => "cp",
"source" => "leaveurdream" // you can name it anything you want
);
//get the gmail login url
$clientUrl = "https://www.google.com/accounts/ClientLogin";
//initialize the curl object
$curl = curl_init($clientUrl);
//set curl option to indicate that we are doing POST
curl_setopt($curl, CURLOPT_POST, true);
//pass the post data array as parameters
curl_setopt($curl, CURLOPT_POSTFIELDS, $clientPost);
//set the following line for SSL and authentication
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
//set option for not checking the peer's certificate
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
//do not echo the data in the browser but save it as string
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
//get the response after executing our curl
$response = curl_exec($curl);

//perform a regular expression match to get the auth key from $response variable
//if the auth key is found then user is logged in successfully else login has failed
preg_match("/Auth=([a-z0-9_\-]+)/i", $response, $matches);
$auth = $matches[1];
//echo the auth key
echo $auth;
?>

3 comments:

Unknown said...

how to use this auth id

Unknown said...

how to use thi s auth id?
pls describe with example..

Sudhir Bastakoti said...

Hi Sandeep,
The auth will have some authentication id (when logged in successfully), after that you can access gmail contact list, gmail calendar, etc according to your requirements. Check my post http://www.sudhirhub.com/search/label/Gmail%20Login%20using%20curl on what to do after getting valid auth id from gmail.
Hope that helps.