Hello! In this post i will show you how to export gmail contacts in PHP after entering the gmail credentials using google oauth2. It will display all google contacts of that particular Email account and also i will give you option to from where you can download those contact in excel sheet. This whole google OAuth cycle is basically based on how to access the third party data. After passing through a strong authorization, we get some access permission with the help of client id and password. And that data is used for getting access token and code and that key is used for further accessing the complete details by accessing the google API.
Before going to complex coding part just have a look over these basic terminology listed below.
Google OAuth:
OAuth is known as “open standard for authorization” and provide a strong authorization scheme on behalf of owner. OAuth was started with oauth1.0, but it has been deprecated and replaced with oauth2.0. You have to make sure that you are using oauth2.0
OAuth Code: We only get this code while we are successfully authorized. After getting OAuth Code code we can request for the access token.
Access Token: This token is key to get the content from the website server. We send request for the access token with authorized code after this we get the access token. With this token, we can access most of the API and also we can collect the data according to our requirements.
Refresh Token: Refresh token is not a separate token ( Often! we are confused with refresh the token ) even though it is same access token. But it’s value got refreshed after leaving one complete flow or logout from your session.
So Simply get the access token and maintain its session until you get logout and the next time when you try to re-login, you will get a new access token which is known as refresh token .
Export gmail contacts in php
Steps for getting the google contacts : here we are explaining step-by-step process for accessing the google contacts.
Step :1
In this step you have to make one google oauth registration in google developer console for accessing the google api, please visit ‘https://console.developers.google.com/project’ to create google api and follow these steps.
- Go to the Google Developers Console.
- Select a project, or Create New Project.
- Type your project name in the Project name field.
- In the Project ID field, optionally type in a project ID for your project. This ID must be unique world-wide.
- Click on Create button and wait for the project to be created.
- Click on the new project name to start editing the project.
- Under “APIs & auth” In the sidebar , select Consent screen.
- Choose an Email and specify a Product Name.
- Under “APIs & auth” In the sidebar, select Credentials.
- Click on Create a new Client ID .
- Register the origins from which your app is allowed to access the Google APIs. An origin is a unique combination of protocol, hostname, and port.
- select Web application, In the Application type section of the dialog .
- Enter the origin for your app In the Authorized JavaScript origins field. You can enter multiple origins to allow for your app to run on different protocols, domains, or subdomains.
- In the example below, Wildcards are not allowed. the second URL could be a production URL.
http://localhost:8080
https://myproductionurl.example.com - Delete the default value from the Authorized redirect URI field. Redirect URIs are not used with JavaScript APIs.
- Click on the Create Client ID button.
- Copy the Client ID ( In the resulting Client ID for web application section ) that your app will need to use to access the APIs.
just after completion you will get a client id and secret key.
Step :2
we have already gotten the client id and secret key. Now, we will use these credential for login window or login page ‘index.php’ while we execute this page. We will get window asking for ‘sign in with google ‘ when we click on this button. We will sent to gmail login window and after entering the gmail credential it directly redirected to our google API. Here user is asked for giving Allow and deny the access. If he click on Allow button, he is redirected to the callback page here we can see our google contacts and can import them in excel sheet.
index.php
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
<html> <head> <link href="css/style.css" rel="stylesheet" type="text/css"/> <link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro|Open+Sans+Condensed:300|Raleway' rel='stylesheet' type='text/css'> <title>Export Google Contacts Using PHP</title> </head> <body> <div class="col-sm-6 col-md-4 col-lg-2"> <div class="col-sm-6 col-md-4 col-lg-2"> <header class="col-sm-6 col-md-4 col-lg-2"> <center> <h2>Export Gmail Contacts With Google Oauth PHP</h2> </center> </header> <hr> <div class="col-sm-6 col-md-4 col-lg-2"> <center> <h3 id ="sign">Sign In with Google for retrieving Contacts</h3> <div class="col-sm-6 col-md-4 col-lg-2"> <a href="https://accounts.google.com/o/oauth2/auth?client_id=265965648617-0onbet13e081upbrtkt4kvtq86l0hr7h.apps.googleusercontent.com&redirect_uri=https://www.tutorialswebsite.com/callback.php&scope=https://www.google.com/m8/feeds/&response_type=code">Export from Gmail</a> </div> </center> </div> </div> </div> </body> </html> |
Step :3
Here you will display all the gmail contacts , we are using access token for accessing the google contacts.
callback.php
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 |
<?php session_start(); ?> <?php $accesstoken = ''; $max_results = 500; $client_id = '265965648617-0onbet13e081upbrtkt4kvtq86l0hr7h.apps.googleusercontent.com'; $client_secret = 'fei5rGxpIhs7xq_mb9f40les'; $redirect_uri = 'https://www.tutorialswebsite.com/callback.php'; $simple_api_key = 'AIzaSyB_IOM7pfIAc3OEFZZBC5LpoACPPgwJ_hg'; $auth_code = $_GET["code"]; function curl_file_get_contents($url) { $curl = curl_init(); $userAgent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)'; // This can also be set when initializing a session with curl_init(). curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($curl, CURLOPT_USERAGENT, $userAgent); curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE); curl_setopt($curl, CURLOPT_AUTOREFERER, TRUE); curl_setopt($curl, CURLOPT_TIMEOUT, 10); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); $contents = curl_exec($curl); curl_close($curl); return $contents; } $fields = array( 'code' => urlencode($auth_code), 'client_id' => urlencode($client_id), 'client_secret' => urlencode($client_secret), 'redirect_uri' => urlencode($redirect_uri), 'grant_type' => urlencode('authorization_code') ); $post = ''; foreach ($fields as $key => $value) { $post .= $key . '=' . $value . '&'; } $post = rtrim($post, '&'); $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, 'https://accounts.google.com/o/oauth2/token'); curl_setopt($curl, CURLOPT_POST, 5); curl_setopt($curl, CURLOPT_POSTFIELDS, $post); curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); $result = curl_exec($curl); curl_close($curl); $response = json_decode($result); if (isset($response->access_token)) { $accesstoken = $response->access_token; $_SESSION['access_token'] = $response->access_token; } if (isset($_GET['code'])) { $accesstoken = $_SESSION['access_token']; } if (isset($_REQUEST['logout'])) { unset($_SESSION['access_token']); } $url = 'https://www.google.com/m8/feeds/contacts/default/full?max-results=' . $max_results . '&oauth_token=' . $accesstoken; $xmlresponse = curl_file_get_contents($url); if ((strlen(stristr($xmlresponse, 'Authorization required')) > 0) && (strlen(stristr($xmlresponse, 'Error ')) > 0)) { echo "<h2>OOPS !! Something went wrong. Please try reloading the page.</h2>"; exit(); } $xml = new SimpleXMLElement($xmlresponse); $xml->registerXPathNamespace('gd', 'http://schemas.google.com/g/2005/Atom'); $result = $xml->xpath('//gd:email'); foreach ($result as $title) { $arr[] = $title->attributes()->address; echo $title->attributes()->displayName; } //print_r($arr); foreach ($arr as $key) { //echo $key."<br>"; } $response_array = json_decode(json_encode($arr), true); // echo "<pre>"; // print_r($response_array); //echo "</pre>"; $email_list = ''; foreach ($response_array as $value3) { $email_list = ($value3[0] . ",") . $email_list; } ?> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=windows-1252"> <title>Export Google Contacts Using PHP</title> </head> <body> <div id="main" > <div class="col-sm-6 col-md-4 col-lg-2"> <div class="col-sm-6 col-md-4 col-lg-2"> <header id="sign_in"> <h2> <form action='csvdownload.php' method='post'> <input type='text' value= '{{{PHP3}}}' name='email' style='display: none'> <input type='submit' width='100' name="importexcel" value='submit'> </form> Export Gmail Contacts<a href='https://www.google.com/accounts/Logout?continue=https://appengine.google.com/_ah/logout?continue=https://www.tutorialswebsite.com/index.php' >Logout</a></h2> </header> <hr> <div class="col-sm-6 col-md-4 col-lg-2"> <div class="col-sm-6 col-md-4 col-lg-2"> <div class="col-sm-6 col-md-4 col-lg-2"> <table cellspacing='0'> <thead> <td id="name">S.No</td> <td>Email Addresses</td> </thead> <?php $count = 0; foreach ($result as $title) { ?> <tr> <td><?php echo $count; $count++ ?></td> <td><?php echo $title->attributes()->address; ?></td> </tr> <?php } ?></table> </div> </div> </div> </div> </div> </div> </body></html> |
csvdownload.php
This script will show you how to download the export google contacts in excel sheet , we are getting the data as string and here we are using scripts for printing them for spread sheet format.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<?php $data = $_POST['email']; $arry[] = explode(',', $data); foreach ($arry as $row) { $arlength = count($row); for ($i = 0; $i < $arlength; $i++) { $farry[] = explode(',', $row[$i]); } } header("Content-type: text/csv"); header("Content-Disposition: attachment; filename=file.csv"); header("Pragma: no-cache"); header("Expires: 0"); $file = fopen('php://output', 'w'); fputcsv($file, array('Description')); foreach ($farry as $row) { fputcsv($file, $row); } exit(); |
Conclusion :
After reading the above post, I am sure you will give a try to the script provided and implement it in your own projects as well. Feel free to visit our website again in the future to get in touch with new coding tricks. You can let us know about your feedback in the space provided below
Pradeep Maurya is the Professional Web Developer & Designer and the Founder of “Tutorials website”. He lives in Delhi and loves to be a self-dependent person. As an owner, he is trying his best to improve this platform day by day. His passion, dedication and quick decision making ability to stand apart from others. He’s an avid blogger and writes on the publications like Dzone, e27.co