9lessons programming blog
Loading Search
9lessons Bring Friends
Wall Script
Follow Me:
Monday, June 13, 2011

Import GMail Contacts Google OAuth Connect with PHP.

Inviting friends is the most important part of the web project success. This post explains you how to import Gmail contacts from address book via Google open authorization protocol connect with PHP. It’s simple just few configurations follow below four steps, use this script and give option to invite more friends.

Importing GMail Contacts Google OAuth Connect with PHP.

Download Script     Live Demo

Step 1
Add or register your domain at click here.
Importing GMail Contacts Google OAuth Connect with PHP.

Step 2
Verify your domain ownership with HTML file upload or including META tag.
Importing GMail Contacts Google OAuth Connect with PHP.

Step 3
Google will provide you OAuth consumer key and OAuth consumer secret key.
Importing GMail Contacts Google OAuth Connect with PHP.

Step 4
Download script configurations.

Config.php
You have to change Oauth keys and return URL.
<?php
$consumer_key='demos.9lessons.info';
$consumer_secret='Eeqmv3xxEO2lfA_rM1uVXZ3M';
$callback='http://demos.9lessons.info/gmail/Contacts.php';
$emails_count='500'; // max-results
?>

GmailConnect.php
Contains PHP code. Connecting to Google for requesting open authentication access tokens.
<?php
include_once 'GmailOath.php';
include_once 'Config.php';
session_start();
$oauth =new GmailOath($consumer_key, $consumer_secret, $argarray, $debug, $callback);
$getcontact=new GmailGetContacts();
$access_token=$getcontact->get_request_token($oauth, false, true, true);
$_SESSION['oauth_token']=$access_token['oauth_token'];
$_SESSION['oauth_token_secret']=$access_token['oauth_token_secret'];
?>

<a href="https://www.google.com/accounts/OAuthAuthorizeToken?oauth_token=<?php echo $oauth->rfc3986_decode($access_token['oauth_token']) ?>">
<img src='Googleconnect.png'/>
</a>

Contacts.php
Google return to Contact.php file with contacts data.
<?php
include_once 'GmailOath.php';
include_once 'Config.php';
session_start();
$oauth =new GmailOath($consumer_key, $consumer_secret, $argarray, $debug, $callback);
$getcontact_access=new GmailGetContacts();
$request_token=$oauth->rfc3986_decode($_GET['oauth_token']);
$request_token_secret=$oauth->rfc3986_decode($_SESSION['oauth_token_secret']);
$oauth_verifier= $oauth->rfc3986_decode($_GET['oauth_verifier']);
$contact_access = $getcontact_access->get_access_token($oauth,$request_token, $request_token_secret,$oauth_verifier, false, true, true);
$access_token=$oauth->rfc3986_decode($contact_access['oauth_token']);
$access_token_secret=$oauth->rfc3986_decode($contact_access['oauth_token_secret']);
$contacts= $getcontact_access->GetContacts($oauth, $access_token, $access_token_secret, false, true,$emails_count);

//Email Contacts
foreach($contacts as $k => $a)
{
$final = end($contacts[$k]);
foreach($final as $email)
{
echo $email["address"] ."<br />";
}
}?>
Comments
{ 118 comments }
Anonymous said...

Thank you for this! Now if only we had Hotmail and Yahoo imports. heh

Shashi kanth said...

Great post... really like this. Appreciate the efforts of the author.

Saranya said...

Gr8 Post..u rock:)

羽化 said...

thanks, great post...it helps alot~~~

Freddie Lore said...

Thanks for this...

Sandy said...

wow great..
btw how to import inbox from google?
any idea?

thx before..

Anonymous said...

Gracias, justo lo que necesitaba

Anonymous said...

Warning: Invalid argument supplied for foreach() in /home/kokkoroc/public_html/demos/gmail/Contacts.php on line 69

Me dio error!! creo que no tengo ningún contacto!!!

(0 Contacts)

satyanarayana panchala said...

hi srinivas, Is there any limit to retrieve gmail contacts?

Srinivas Tamada said...

@satyanarayana

Change at config.php $emails_count='500';

Anonymous said...

How can we import contacts from facebook?

Abdelaziz said...

Hello,

Your script seems very good, but it return this warning:

Warning: Invalid argument supplied for foreach()

in the Contacts.php file

How can I solve this one?

Thank you

e11world said...

Absolutely useful! Thank you very much!

Anonymous said...

how can we import emails from google account ?

honlapkészítés said...

Great post! Thank you!

Harpreet Singh said...

Nice post....great work keep it up...

Rohith said...

How to extract the first and last name along with the email ids.?

adiputra said...

wew,,nice tutorial bro..i will try this tutorial later..thanks..:)

Mary said...

How to print Name?

I am using below code which doesn't work:

$nameArr = $contacts[$k]["title"];
foreach($nameArr as $name)
{
echo "
Name: ".$name["$t"] ."
";
}

Vaibhav said...

To capture name, add this line:

$name = end($contacts[$k]["title"]);

Vineet Arora said...

I'm still waitin for email to be subscribed in your mailing list to download gmailOath.php but I got a flair that the script is wonderful. Thanx bro. U rock. I'd been trying this in jan - feb then hopelessely quit it.
U made my day :) Cheers to u... Do let me know if I can proove some help to u

Tasked Us said...

how do you modify the script to import groups and group members?

Anonymous said...

Mr Srinivas Tamada i get the following error when i use your script with my website please help me fix them.....
Notice: Undefined variable: argarray in /GmailConnect.php on line 7

Notice: Undefined variable: debug in /GmailConnect.php on line 7

Notice: Undefined index: port in /GmailOath.php on line 338
Google Oauth Connect

Anonymous said...

Hello

your demo seems good but its not work for me because its show a warring

"Warning: Invalid argument supplied for foreach() in /home/a2089058/public_html/you_email/GmailContacts/Contacts.php on line 18
"

Anonymous said...

Hello
Thanks for this wonderful script but it is not working for me. because its show a warring "Warning: Invalid argument supplied for foreach() in /home/a2089058/public_html/you_email/GmailContacts/Contacts.php on line 18
" please solve this problem
thanks in advance.

Anonymous said...

Hello,

Thanks for this wonderful script.

RAJASEKARAN.....T said...

Can u help me for Yahoo mail contacts importer

Vineet Arora said...

I'm havin the same problem! invalid...foreach
Tried to change the script ! Not working anyhow

Kindly explain the script if you can or kindly try to solve the problem
Thanks

Kapry said...

Thank you for this!
lol

Anonymous said...

Yeah, this is great. Pls provide also yahoo and window live. Absolutely useful.

Vineet Arora said...

We are still waiting for invalid...foreach solution, Kindly post it soon

Ankit said...

Guys post some direct url to download the script, i would like to get hands on the script.

kama said...

Great post, tested on different browsers, but Chrome doesn't show contacts.... :(( , why?

Delphi said...

I may have done something wrong.
When i test on my server i get: Invalid Token.
get_request_token is not responding with a token.
Please, help

Delphi said...

Hi
I can not make it work.
I got invalid token.
get_request_token is not returning a token.
What can i do?

kay said...

Hello everyone,
when i hosted this example on my site, i got a "Invalid Token." response from Google with the URL as https://www.google.com/accounts/OAuthAuthorizeToken?oauth_token=

Saint said...

I'm havin the same problem!
invalid...foreach
$contacts= $getcontact_access->callcontact($oauth, $access_token, $access_token_secret, false, true,$emails_count);
it always return the NULL.
any one now why...?

Parikshit said...

Warning: Invalid argument supplied for foreach()
I can help to fix the error...

Open GmailOath.php
navigate to GetContacts function(it is at the end of the file) and look for
$params['max-results'] = '500';

change that value to
$params['max-results'] = '99999';
save the file.
Go to ur browser preference and clear the cookies that your website has saved on the local system.
Then try running it again!
Vola!!! it works! (does it?). :)

kama said...

Hey, could you please answer my question, why every browser returns data, but Chrome doesn't?

John M said...

What about email sending limits? Even if you use Google Apps account, you can only send 500 emails at a time (what a bout contact lists with hundreds of emails)?

Dan said...

How to know if the user denied the application?

Hekmat said...

really really nice application !! Thaaaaaaaaaank you!

Hekmat said...

but i want to know how can load google access page in popup? :)

Anonymous said...

problem in downloading : GmailOath.php

po said...

my problem:

+++2011-11-16T00:50:28-0200:signature_base_string:INFO:normalized_base_string:GET&https%3A%2F%2Fwww.google.com%2Faccounts%2FOAuthGetRequestToken&oauth_callback%3Dhttp%253A%252F%252Fwww.youcall.com.br%252Fgmail%252F%252FContacts.php%26oauth_consumer_key%3Dwww.youcall.com.br%26oauth_nonce%3D1557113082%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1321411828%26oauth_version%3D1.0%26scope%3Dhttps%253A%252F%252Fwww.google.com%252Fm8%252Ffeeds
+++2011-11-16T00:50:28-0200:getreqtok:INFO:request_url:https://www.google.com/accounts/OAuthGetRequestToken?oauth_callback=http%3A%2F%2Fwww.youcall.com.br%2Fgmail%2F%2FContacts.php&oauth_consumer_key=www.youcall.com.br&oauth_nonce=1557113082&oauth_signature=QIZFnpZdiola3yABuon2SfzZaWo%3D&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1321411828&oauth_version=1.0&scope=https%3A%2F%2Fwww.google.com%2Fm8%2Ffeeds
+++2011-11-16T00:50:29-0200:getreqtok:INFO:response_body_parsed:

Anonymous said...

OK here is the solution for the datetime problem:

function get_linkedin_current_time() {
date_default_timezone_set("America/Los_Angeles");

$ch = curl_init("http://api.linkedin.com");
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);

$response = curl_exec($ch);
foreach(explode("\r\n", $response) as $line) {
if(substr($line, 0, 5) == "Date:") {
return strtotime(trim(substr($line, 5)));
}
}

return -1;
}

printf("Local time deviates from LinkedIn time by: %d seconds", get_linkedin_current_time() - time());

use the code above to learn time difference between your server and linkedin server (google server will be the almost same) than in GmailOauth.php change every time function to "time()+2175"(seconds you found using the above function)

money by google said...

how can get OAuth consumer key

Anonymous said...

hi sri I m getting
Warning: Invalid argument supplied for foreach() in /home/awebthou/public_html/gmail/Contacts.php on line 20

Please help me

Ecstasy Forum said...

Hi,

This is a nice post. But there is an quick authentication method implemented using Gmail OAuth itself @ http://www.ecstasyforum.com. This needs almost 10% of serverside coding that fetches user's details such as email, picture URL, name,gender.

Implementation guided by http://code.google.com/apis/accounts/docs/OAuth2Login.html

dev said...

Hello,

Your script seems very good, but it return this warning:

Warning: Invalid argument supplied for foreach()

in the Contacts.php file

How can I solve this one?

Thank you

Nikhil said...

where is GetContacts()
function in GmailGetContacts class

praveen.u said...

am creating a simple gadget which get user address form google.......
i dono how to approach this
could any one help me

Anil kumar said...

I'm getting this warning
Warning: Invalid argument supplied for foreach() in /home/utreemmx/public_html/Contacts.php

Anonymous said...

The Script is not working I am getting the following error:

syntax error, unexpected T_STRING, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or '}' on line 11

Can Any one help.....

Anonymous said...

Problme in downloading GmailOath.php

Hnery said...

Is there any way to retrieve emails as well using OAuth, i have used IMAP but it doesn't provide complete functionality i want and also don't shows the message body for emails marked as important ???

amprodes said...

YOU ARE MAYBE HAVING THE FOREACH because you are redirecting the callback with an including file where the oauth_token was created so when the callback file try to read the session is not the same that google was already authorized so $contacts its empty thats why

hassan said...

There is a problem if i have imported contacts and i refresh the page then it gives error of Warning: Invalid argument supplied for foreach(). Due you have any idea, how to solve it.

all Asian said...

Its working fine....

Import email and name
--------------------------------

foreach($contacts as $k => $a)
{
$final = end($contacts[$k]);

foreach($final as $email)
{
echo $email["address"] ."
";
echo $name = end($contacts[$k]["title"]);



}
}

vasu said...

where is GmailOath.php file

vasu said...

where is GmailOath.php

GulMerve said...

I need this project in Java language. How can I fnd please help me.

Ankur Jain said...

Gr8 post Dear! Very simple just follow the steps.

Jeevan said...

very useful post, thanks to author.

Can I retrieve other details of contacts like name, phone number, photo etc?
If it is so, how?

Nida Balol said...

hello can anyone tell me how i can get phone number also :)

Anonymous said...

how i can change contact.php to other file

Anonymous said...

How I can download source code? Please, help!

Rakesh Jain said...

is anybody resolve this problem
Warning: Invalid argument supplied for foreach() in

?

Anonymous said...

Hi srinivas,
I am using your script ..I ve an issue..get_access_token() function should return an array but in my case it returns like this

Array ( [signature_invalid base_string:GET] => [https%3A%2F%2Fwww.google.com%2Faccounts%2FOAuthGetAccessToken] => [oauth_consumer_key%3Dwww.webmisto.com%26oauth_nonce%3D95334506%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1340628064%26oauth_token%3D4%252F9INdziiEXi2PkQ7g-WNVAy5ygFyx%26oauth_verifier%3DqN9_SjQYHHk4N1fZQ5Z9U7ik%26oauth_version%3D1.0 ] => )

thats why i cant access key value of returned array..Can you pls help me finding its solution??

Anonymous said...

this api is depreciated now

Anonymous said...

So any one have other idea to use this application ?

Brindha Honey said...

Hi,

This is nice tutorial.It's very helpful for me. May i know how to get contacts name and photo in gmail. please help me it's urgent.

Vijay lathiya said...

Hi kay, Delphi and all friends
if u got invalid token response than first set your system and/or server time properly.

i hope invalid token issue solve.

tks srinivas for very great post.

Rayen said...

Very good tutorial!

naveen voruganti said...

after getting the contacts i am refresh the page then no contacts is displayed.but i want to show that contacts how?

King said...

Warning: Invalid argument supplied for foreach() in /home2/link5943/public_html/friendways.com/gmail/Contacts.php on line 18

Please help me to resolve this warning

Anonymous said...

hi sir

plz can you help me to solve this problem.

Warning: Invalid argument supplied for foreach() in /home/googlecl/public_html/friendstohelp/invite/Contacts.php on line 26

chukwuka chime said...

i keep getting this when i run the script
Fatal error: Maximum execution time of 30 seconds exceeded in C:\wamp\www\test\GmailConnect.php on line 5

chukwuka chime said...

cannot see token in url

pov said...

Hey admin page! I see a lot of command has problem but i don't see your reply. why that? It's not good if you don't have reply to support what you have.sorry if any bad to you .

Anonymous said...

gr8

Stone said...

Alright since Mr Srinivas is too busy to get back to all of us with the errors mentioned here, I've done us all a favour by figuring out what went wrong in the foreach error.

This is the original code in Contacts.php:

$contacts= $getcontact_access->GetContacts($oauth, $access_token, $access_token_secret, false, true,$emails_count);
foreach($contacts as $k => $a)
{
$final = end($contacts[$k]);
foreach($final as $email)
{
echo $email["address"] ."
";
}
}

Now here's the change in the code that I edited:

$contacts= $getcontact_access->GetContacts($oauth, $access_token, $access_token_secret, false, true,$emails_count);
$cont=$contacts;
foreach($contacts as $k => $a)
{
$final = end($contacts[$k]);
foreach($final as $email)
{
echo $email["address"] ."
";
$contacts=$cont;
}
}

Basically, the $contacts was getting over-written in with each loop. $cont serves as a backup for $contacts and every time the email id is printed, the $contacts variable will be reinitialized with the original value.

Long story short, it works! You might have to close your browser, refresh a few times and clear your cache to clear the temp memory. It'll work after that!

Cheers!

reporting business said...

hi, thanks very much for this post! extremely useful!!! anthony

Unknown said...

Hi,

Is there any way in which user can select the contacts and import the selected contacts only ?

Thanks in Advance.

abdallah awwad alkhwaldah said...

solve for foreach proplem
rfc3986_decode($_GET['oauth_token']);
echo "Request token :".$request_token;
echo "
";

//$request_token='k57356v';
$request_token_secret=$oauth->rfc3986_decode($_SESSION['oauth_token_secret']);
echo "Request token secret :".$request_token_secret;
echo "
";

//$oauth_verifier= 'pkzkns';
$oauth_verifier= $oauth->rfc3986_decode($_GET['oauth_verifier']);
echo "Request token verifier :".$oauth_verifier;
echo "
";

echo "access token info
";

$retarr = $getcontact_access->get_access_token($oauth,
$request_token, $request_token_secret,
$oauth_verifier, false, true, true);

////////////////////////////////////////////////////////////////////
// Call Contact API

echo "
";

$access_token=$oauth->rfc3986_decode($retarr['oauth_token']);
echo "Access token :".$access_token;
echo "
";

$access_token_secret=$oauth->rfc3986_decode($retarr['oauth_token_secret']);
echo "access token sectet :".$access_token_secret;
echo "
";

$contac_list= $getcontact_access->GetContacts($oauth, $access_token, $access_token_secret, false, true,true);
foreach($contac_list as $k => $a)
{
$final = end($contac_list[$k]);

foreach($final as $email)
{
echo $email["address"] ."
";
echo $name = end($contac_list[$k]["title"]);



}
}
?>

Nazim Hasan said...

thanks for good post but i have one issue if user denied the permission so api is not redirecting to my site url. May u plz help me?

Jack said...

Thanks, it help alot.

Umair said...

want Gmail and twitter invitation like thefancy.com can anybody please help me I want to use it in leadconcept.com/wishthing. Gmail popup opens but it dosent work anymore. :(
Plz guid me or email me the solution.

Anonymous said...

Thank you so much for this wonderful help.. I cannot download source code yet but I got GmailOath.php file here..

https://code.google.com/p/rspsms/source/browse/trunk/system/plugins/GmailContacts/GmailOath.php?r=11

Thanks again and its working for me :)

Glikemični indeks said...

I tried many other solutions, mainly as modules, but neither worked. Thanks for this solution that works!

Ashish said...

I have noticed that this works pretty well on my local machine but when you put this inside a framework the contacts API results nothing.

I found another solution which is CURL and oAuth2.0 based http://25labs.com/import-gmail-or-google-contacts-using-google-contacts-data-api-3-0-and-oauth-2-0-in-php/

I hope this will help someone looking to import gmail contact (especially having issues with this api) for rest this API works like charm.

Cheers.

Anonymous said...

I think the main problem for the "foreach", is that we don't get back the request_token_secret. If you print the strings, you will see what I am talking about. Just add this before the "foreach" and try it:

echo "request token:$request_token
";
echo "request token secret:$request_token_secret
";
echo "oauth verifier:$oauth_verifier
";
echo "access token:$access_token
";
echo "access token secret:$access_token_secret
";

You will see that only the request_token and the oauth_verifier are not empty.

So the question is:
HOW CAN I GET THE REQUEST_TOKEN_SECRET?

Bangladesh Jobs said...

Its working fine....

Import email and name
--------------------------------

foreach($contacts as $k => $a)
{
$final = end($contacts[$k]);

foreach($final as $email)
{
echo $email["address"] ."
";
echo $name = end($contacts[$k]["title"]);



}
}

adnan khan said...

I follow the above steps but get error:

Warning: Invalid argument supplied for foreach() in /home/content/18/11254218/html/missymtoyz/Contacts.php on line 16

prads said...

Notice: Undefined index: port in /var/www/html/gmail/GmailOath.php on line 338

Daifallah Al-Hasni said...

I try it , AA+,
Please I want to import Name And PhoneNumber

I cloud not, can you help me

Thanks

atul blog said...

hi what is Upload new X.509 cert:
(Optional) .PEM GOOGLE SHOW invelid file how to creat x.509 fil pem formate

Deepak said...

can you activate subscription for my email : deepakrt@gmai.com

I looking forward to download this scritp. May I know where I can find "GmailGetContacts" class. Thanks

Bunty Roy said...

Few month ago it was working well, but now it throwing an error "Timestamp is too far from current time: 1375191942"

Please help me to resolve this issue.

Testuser.testing said...

hello all,

i have problem in get contact


[signature_invalid
base_string:GET]

please reply ....fast

karthick r said...

chrome browser it not working.
why it is serverside scripting.
help me.

Webdesignworld said...

Great tutorial. Was looking for it.

SĦußħåm Vëŕmå said...

Really it's g8 tutorial....
If you are facing problem in the foreach loop:

foreach($contacts as $k => $a)
{
$final = end($contacts[$k]);
foreach($final as $email)
{
echo $email["address"] ."
";
}
}

Just us the is_array function like this:

if (is_array($contacts))
{
foreach($contacts as $k => $a)
{
$final = end($contacts[$k]);
foreach($final as $email)
{
echo $email["address"] ."
";
}
}
}

Anonymous said...

Hi.
First of all thank you for this post.
I'm having a little issue. When I get to implement all the files, altough I change the required fields like the $consumer_key and stuff, when I click my button, it asks me to give authorization to this site's request, instead of mine. And changing other fields causes the token to corruopt itself and stop working.
Any ideas? thanks!

Murad khan said...

nice script. can you make such a nice script for yahoo contacts. thanks

Anonymous said...

hello

when i try to run this script its show me below some error.

Notice: Undefined variable: argarray in C:\Xampp\htdocs\GmailContacts\GmailConnect.php on line 5

Notice: Undefined variable: debug in C:\Xampp\htdocs\GmailContacts\GmailConnect.php on line 5
When i try tr

Notice: Undefined index: port in C:\Xampp\htdocs\GmailContacts\GmailOath.php on line 338

Notice: Undefined offset: 1 in C:\Xampp\htdocs\GmailContacts\GmailOath.php on line 281

Notice: Undefined index: oauth_token in C:\Xampp\htdocs\GmailContacts\GmailConnect.php on line 8

Notice: Undefined index: oauth_token_secret in C:\Xampp\htdocs\GmailContacts\GmailConnect.php on line 9

vaishali manvar said...

Hi.
First thanks for this post.
i have implement this gmail contact importers but i want to change the domain name or i want to register the new domain but i find the difficulties in to search the link of add register domain. so please give me the link so i can follow the above step.

Doolam said...

Error: invalid_request auth problam pls

vj salman said...

How i create customer key?

ravinder payal said...

how can we add client id for consent screen

karthick said...

Thanks for the post. I am getting email-d and title.Is it possible to get friends image ?

wdwtest said...

Hello Srinivas!

Script works Gr8! Thanks for this.
But Facing 1 problem, when user is asked to allow permission to manage contacts , it displays Client Id for application. And I don;t want it there.
Can you please suggest solution for the same. I will like to have site name there.

Thank You

Selva Kumar said...

How can i implement this in YII Framework?

Alex Babiev said...

How can I take telephone numbers from Google Contacts?

Anonymous said...

greAT

ganesh said...

Hello Srinivas,
iam getting gmail contacts but when i refresh the page contacts not display's

nida zehra said...

Hello Srinivas,
This good works right for me , but how can i fetch the picture or any other contacts given ??? does the array returned contains the info??? how can i access it???

Anonymous said...

hello,
I got an error : Warning: Invalid argument supplied for foreach() in /home/kokkoroc/public_html/demos/gmail/Contacts.php on line 69

what is the solution for this error and i would like to fetch the image/profile picture if the user as well as his/her name.
any help will be greatfull

nice work Tamada ji

Post a Comment