Hello everyone,

I had to write a class to import a Gmail address book so I decided to share.

As you will see it’s fairly simple.

<?php

class GoogleContact
{
    private $email;
    private $pass;
    private $auth;

    public function __construct($email, $pass){
        $this->email = $email;
        $this->pass = $pass;
    }

    public function login(){
        $url = "https://www.google.com/accounts/ClientLogin";
        $post = array("accountType"=>"HOSTED_OR_GOOGLE","Email"=>$this->email,"Passwd"=>$this->pass,"service"=>"cp","source"=>"GoogleContact");
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL,$url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

        $retour = curl_exec($curl);

        if(preg_match("/Error/",$retour)){
            return false;
        } else {
            $auth = explode("Auth=",$retour);
            $this->auth = $auth[1];
            return true;
        }
    }

    public function fetchContact(){
        $authHeader = array('Authorization: GoogleLogin auth='.$this->auth);
        $url = "http://www.google.com/m8/feeds/contacts/default/full?max-results=1000";
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL,$url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $authHeader);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $retour = curl_exec($curl);
        $matches = array();
        preg_match_all("/address='([A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4})'/i",$retour,$matches);
        return $matches;
    }

}
?>

And you can use this way :

<?
$g = new GoogleContact("djpate@gmail.com","youwish");
if($g->login()){
    $contacts = $g->fetchContact();
    print_r($contacts);
} else {
    echo "Access denied";
}
?>

Have fun guys !

Share

Related Posts:

  • No Related Posts