Hello! This post is all about saving the google contacts in your google account, there is no library used in this script code. This script is totally based on curl function and also integrated with google application(Google OAuth). On running this script user will get a contact form asking for some field to be inserted, which are listed below: –

  1. Name
  2. Last Name
  3. Email
  4. Phone Number

After filling the form user will submit it and then user will be sent for google authentication. In google authentication user have to enter their Gmail ID and password,  as soon as user complete this authentication user will be redirected to another page displaying message ‘contact added’. User’s are provided with two more option which is Logout and previous image sign. As per requirement, user can Logout or go to the previous page.

After completing all the procedure, user can check contacts details available in the account. The inserted contact details will get added in the account.


Watch the live demo or download code from the link given below


For Complete solution, you can take a look at our premium service MailGet – email service provider. It offers a well-managed email list and other advanced services to its users which helps them to manage their contact lists systematically.


Now come to the coding part, this script contains two Php file named ‘index.php‘ and  ‘callback.php‘ along with separate images and CSS folder.

Index.php

This page will display a contact form. When a user will fill the contact form, all the values will be passed to callback.php page using GET method.
These passed value will be retrieve and stored in callback.php file.

<html>
<head>
<title>Insert Contacts in Google Using PHP</title>
<link href="bootstrap/css/bootstrap.css" rel="stylesheet" type="text/css"/>
<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'>
</head>
<body>
<div class="container-fluid">
<h1>Insert Contacts in Google Using PHP</h1>
<div id="login">
<div id="h2" class="h2 row">
<div class="col-md-12"><h2><span>Insert Contacts in Google</span></h2></div>
</div>
<div class="row">
<div class="col-md-12">
<form action="http://formget.com/tutorial/Import-Google-Contacts-Using-PHP/callback.php?<?php echo http_build_query($data); ?>" method="get">
<input type="text" placeholder="First Name" name="name"/>
<input type="text" placeholder="Last Name" name="lname"/>
<input type="email" placeholder="Contact Email" name="email"/>
<input type="text" placeholder="Phone Number" name="phone"/>
<input type="submit" value="Add Contact" name="submit"/>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
<?php
/**we are fetching the form data from browser using GET method**/
if (isset($_GET['submit'])) {
$data['name'] = $_GET['name'];
$data['lname'] = $_GET['lname'];
$data['email'] = $_GET['email'];
$data['email'] = $_GET['phone'];
}
?>

Callback.php


This page script has major functionality of code , this page is responsible for google authentication as well as adding the contacts of form visitor into the mail account of user.we are using curl function for doing all this there is no library at all.

<?php session_start(); ?>

<html>
<head><link href="css/style.css" rel="stylesheet" type="text/css"/>
<link href="bootstrap/css/bootstrap.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>Import Google Contacts Using PHP</title>
</head>
<body>

<?php
/*****Form data is stored in session variabe because after google authentication the page will be redirected to this page and data will be persist******/
if (isset($_GET['name'])) {
$_SESSION['name'] = $_GET['name'];
$_SESSION['lname'] = $_GET['lname'];
$_SESSION['email'] = $_GET['email'];
$_SESSION['phone'] = $_GET['phone'];
/****this header part is responsible for google authentication ****/
/****After authentication we get authentication code in return****/
header('location:https://accounts.google.com/o/oauth2/auth?client_id=991481336354-m35dqmsq4ubc7gp8433dcb3ampip5tpi.apps.googleusercontent.com&redirect_uri=http://formget.com/tutorial/Import-Google-Contacts-Using-PHP/callback.php&scope=https://www.google.com/m8/feeds/&response_type=code');
}
/**session variable is stored in variable****/
$id1 = $_SESSION['name'];
$id2 = $_SESSION['email'];
$id3 = $_SESSION['lname'];
$id4 = $_SESSION['phone'];
?>
<div class="container-fluid">
<h1>Insert Contacts in Google Using PHP</h1>
<div id="login">
<div id="h2" class="h2 row">
<div class="col-md-12"><a href='http://formget.com/tutorial/Import-Google-Contacts-Using-PHP/index.php'> <img src="images/preimg1.jpg" alt="previous" id ="preimg"/></a><h2><span>Insert Contacts in Google</span></h2><a href='https://www.google.com/accounts/Logout?continue=https://appengine.google.com/_ah/logout?continue=http://formget.com/tutorial/Import-Google-Contacts-Using-PHP/index.php' ><img src='images/logoutimg1.png' alt='logout'id ='logoutimg'/></a></div>
</div>
<div class="row">
<div class="col-md-12">
<div class="row">
<div class="col-md-12">
<p>Contact Added</p>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
<?php
$client_id = '<Enter your client id here>';
$client_secret = '<Enter your client secret here>';
$redirect_uri = 'http://formget.com/tutorial/Import-Google-Contacts-Using-PHP/callback.php' ;
$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; .NET CLR 1.1.4322)';

curl_setopt($curl, CURLOPT_URL, $url); //The URL to fetch. This can also be set when initializing a session with curl_init().
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); //TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5); //The number of seconds to wait while trying to connect.
curl_setopt($curl, CURLOPT_USERAGENT, $userAgent); //The contents of the "User-Agent: " header to be used in a HTTP request.
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE); //To follow any "Location: " header that the server sends as part of the HTTP header.
curl_setopt($curl, CURLOPT_AUTOREFERER, TRUE); //To automatically set the Referer: field in requests where it follows a Location: redirect.
curl_setopt($curl, CURLOPT_TIMEOUT, 10); //The maximum number of seconds to allow cURL functions to execute.
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); //To stop cURL from verifying the peer's certificate.

$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, FALSE);
$result = curl_exec($curl);
curl_close($curl);

$response = json_decode($result);
/***Accessing Access_Token and setting the session for access token so that after refreshing the page it will still persist in page***/

if (isset($response->access_token)) {
$accesstoken = $response->access_token;
$_SESSION['access_token'] = $response->access_token;
}

if (isset($_GET['code'])) {
/**access_token session is passed here for data persist after refreshing the page***/
$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)) { //At times you get Authorization error from Google.
echo "<h2>OOPS !! Something went wrong. Please try reloading the page.</h2>";
exit();
}
/**This is main script which is used for contact saving in account,variable declare before is passed here.***/
$access_token = $_SESSION['access_token'];
$contactXML = '<?xml version="1.0" encoding="utf-8"?> '
. '<atom:entry xmlns:atom="http://www.w3.org/2005/Atom" xmlns:gd="http://schemas.google.com/g/2005">'
. ' <atom:category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/contact/2008#contact"/> '
. '<gd:name> <gd:givenName>' . $id1 . '</gd:givenName> <gd:fullName></gd:fullName> <gd:familyName>' . $id3 . '</gd:familyName>'
. ' </gd:name> <gd:email rel="http://schemas.google.com/g/2005#home" address="' . $id2 . '"/> '
. '<gd:im address="[email protected]" protocol="http://schemas.google.com/g/2005#GOOGLE_TALK" primary="true" rel="http://schemas.google.com/g/2005#home"/>'
. ' <gd:phoneNumber rel="http://schemas.google.com/g/2005#home" primary="true">' . $id4 . '</gd:phoneNumber> </atom:entry>';
$headers = array('Host: www.google.com',
'Gdata-version: 3.0',
'Content-length: ' . strlen($contactXML),
'Content-type: application/atom+xml',
'Authorization: OAuth ' . $access_token);
$contactQuery = 'https://www.google.com/m8/feeds/contacts/default/full/';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $contactQuery);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $contactXML);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT, 400);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
$result = curl_exec($ch);
?>

Style.css

This style script is totally used for designing part of forms and pages and it has no concern with main functionality. You can make the form or design of your choice by editing this css file as per your requirements.

@import url(http://fonts.googleapis.com/css?family=Raleway);
body{
font-family:raleway !important;
}
#h2{
background-color: #FEFFED;
text-align:center;
border-radius: 10px 10px 0 0;
border-bottom: 1px solid #ccc;
color: black;
font-weight: bolder;
font-size: 2em;
margin: 0px -15px;
padding: 8% 0;
font-family:raleway !important;
position: relative;
}
.wrap{
width: 33%;
margin: 5% auto;
}
.container-fluid{
width: 45%;
margin: auto auto;
}
#login{
border: 2px solid #ccc;
border-radius: 10px;
font-family:raleway!important;
}
h1{
padding: 6% 0;
font-family:raleway!important;
text-align: center;
}
.h2{
margin: 0 !important;
padding: 2% 0 !important;
}
img{
padding: 0% 0%;
width: 110px;
margin-bottom: -5%;
}
input[type=text],input[type=email]{
width:99.5%;
padding: 10px;
margin-top: 14px;
border: 1px solid #ccc;
padding-left: 5px;
font-size: 16px;
font-family:raleway !important;
}
input[type=submit]{
width: 100%;
background-color:#FFBC00;
color: white;
border: 2px solid #FFCB00;
padding: 10px;
font-size:20px;
cursor:pointer;
border-radius: 5px;
margin-top: 14px;
}
p{
text-align: center;
font-family:raleway !important;
font-size:25px;
padding: 15px;
}
#logoutimg
{
width:9%;
position: absolute;
margin-left: 230px;
margin-top: -63px;
}
#preimg
{
width:7%;
position: absolute;
margin-left: -290px;
margin-top: 21px;
}

Conclusion :

Hope you would have enjoyed this script,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.

You may also like –