loading

How to Add Event to Google Calendar using PHP

How to Add Event to Google Calendar using PHP

How to Add Event to Google Calendar using PHP

0 Sales

Free

The Event Calendar allows you to handle events more efficiently and with a better user experience. Typically, an event calendar is integrated on a web page to list events chronologically. If your online application requires a calendar to arrange events, you may easily create one with PHP. Google Calendar is now the most efficient method to organize activities without worry. Using the REST API, the event generated in the online application may be immediately uploaded to the Google Calendar.

 

The ability to sync with Google Calendar expands the online application's event management capabilities. Using the Calendar API, you may add events to Google Calendar programmatically from the website. With the REST API service, the Google Calendar API makes it simple to add events to Google Calendar. PHP may be used to integrate Google Calendar event add feature seamlessly. This article will show you how to use PHP to build events dynamically in a web application and upload events to Google Calendar from the website.

 

To add an event to Google Calendar using PHP, the following functionality will be required.

- Create an HTML form to gather event information (title, description, location, date, and time).

- Create and store event data in a database.

- From a PHP script, add an event to Google Calendar.

- Show the progress of an event's creation along with a link to Google Calendar.

Take a look at the file structure before beginning to construct a PHP script to add events to Google Calendar using PHP.

 

 

google_calendar_add_event_with_php/
├── config.php
├── dbConfig.php
├── index.php
├── addEvent.php
├── google_calendar_event_sync.php
├── GoogleCalendarApi.class.php
└── css/
    └── style.css

 

 

 

Create Google Project and Enable Calendar API

 

Google Project is necessary in order to obtain the API keys required to perform API calls to Google Calendar. If you already have a Google Application, you may utilise the API keys from it. Simply ensure that the Google Calendar API is activated in this already-existing Google project. If you don't already have any Google apps, follow the steps below to register your app on Google Developers Console and obtain the API keys.

 

1. Navigate to Google API Console.

 

2. Choose an existing project from the list of projects, or click NEW PROJECT to start a new one:

- Enter the Project Name here.

- Under the Project Name section, the project ID will be generated automatically. (Optional) You can edit this project ID by clicking the Edit button, but it should be unique globally.

- Press the CREATE button.

 

3. Enable the Google Calendar API service for the newly established project.

- Select Library from the APIs & Services option in the sidebar.

- In the API list, look for the Google Calendar API service and pick Google Calendar API.

- To enable the Google Calendar API Library, click the ENABLE button.

 

4. Select Credentials from the APIs & Services option in the sidebar.


5. Choose the OAuth consent screen tab and configure the consent screen options.

- Enter the name of the application.

- Select a Support email address.

- Specify the Authorized domains that will be permitted to authenticate using    OAuth.

- Save by clicking the Save button.

 

6. Choose the Credentials tab, then the Add credentials drop-down menu, and then OAuth client ID.

- Select Web application in the App type section.

- Enter the redirect URL in the Authorized redirect URIs area.

- Select the Create option.

 

A dialogue box with OAuth client data will display; record the Client ID and Client secret for subsequent use in the script. You may use this Client ID and Client secret to gain access to the Google Calendar API.

 

 

Create Database Table

 

To save event information on the local server, a table in the database is necessary. In the MySQL database, the below SQL generates an activities table with some simple columns.

CREATE TABLE `events` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `description` text COLLATE utf8_unicode_ci NOT NULL,
  `location` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `date` date NOT NULL,
  `time_from` time NOT NULL,
  `time_to` time NOT NULL,
  `google_calendar_event_id` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `created` datetime NOT NULL DEFAULT current_timestamp(),
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

 

 

Google Calendar API PHP Library

 

Google supplies a PHP library for making Calendar API requests, however it also includes many extra services that comes with a big number of files. To simplify the process, we created a custom library in PHP to handle Google Calendar API calls.

 

Our Google API Library makes it possible to use PHP to authenticate with a Google account and use the Calendar API. The event add process will be handled by this custom PHP library, which will make use of the Google Calendar v3 API.

 

- GetAccessToken() – Using the authentication code, retrieve the authentication code from the Google OAuth 2 API.

 

- GetUserCalendarTimezone() — Retrieves the user's timezone from their Google calendar settings.

 

- GetCalendarsList() – Retrieves the user's calendar list.

 

- CreateCalendarEvent() – Add an event to the users' Google calendar.

/** 
 * 
 * This Google Calendar API handler class is a custom PHP library to handle the Google Calendar API calls. 
 * 
 * @class        GoogleCalendarApi 
 * @author        CodexWorld 
 * @link        http://www.codexworld.com 
 * @version        1.0 
 */ 
class GoogleCalendarApi { 
    const OAUTH2_TOKEN_URI 'https://accounts.google.com/o/oauth2/token'; 
    const CALENDAR_TIMEZONE_URI 'https://www.googleapis.com/calendar/v3/users/me/settings/timezone'; 
    const CALENDAR_LIST 'https://www.googleapis.com/calendar/v3/users/me/calendarList'; 
    const CALENDAR_EVENT 'https://www.googleapis.com/calendar/v3/calendars/'; 
     
    function __construct($params = array()) { 
        if (count($params) > 0){ 
            $this->initialize($params);         
        } 
    } 
     
    function initialize($params = array()) { 
        if (count($params) > 0){ 
            foreach ($params as $key => $val){ 
                if (isset($this->$key)){ 
                    $this->$key $val; 
                } 
            }         
        } 
    } 
     
    public function GetAccessToken($client_id$redirect_uri$client_secret$code) { 
        $curlPost 'client_id=' $client_id '&redirect_uri=' $redirect_uri '&client_secret=' $client_secret '&code='$code '&grant_type=authorization_code'; 
        $ch curl_init();         
        curl_setopt($chCURLOPT_URLself::OAUTH2_TOKEN_URI);         
        curl_setopt($chCURLOPT_RETURNTRANSFER1);         
        curl_setopt($chCURLOPT_POST1);         
        curl_setopt($chCURLOPT_SSL_VERIFYPEERFALSE); 
        curl_setopt($chCURLOPT_POSTFIELDS$curlPost);     
        $data json_decode(curl_exec($ch), true); 
        $http_code curl_getinfo($ch,CURLINFO_HTTP_CODE); 
         
        if ($http_code != 200) { 
            $error_msg 'Failed to receieve access token'; 
            if (curl_errno($ch)) { 
                $error_msg curl_error($ch); 
            } 
            throw new Exception('Error '.$http_code.': '.$error_msg); 
        } 
             
        return $data; 
    } 
 
    public function GetUserCalendarTimezone($access_token) { 
        $ch curl_init();         
        curl_setopt($chCURLOPT_URLself::CALENDAR_TIMEZONE_URI);         
        curl_setopt($chCURLOPT_RETURNTRANSFER1);     
        curl_setopt($chCURLOPT_HTTPHEADER, array('Authorization: Bearer '$access_token));     
        curl_setopt($chCURLOPT_SSL_VERIFYPEERFALSE);     
        $data json_decode(curl_exec($ch), true); 
        $http_code curl_getinfo($ch,CURLINFO_HTTP_CODE); 
         
        if ($http_code != 200) { 
            $error_msg 'Failed to fetch timezone'; 
            if (curl_errno($ch)) { 
                $error_msg curl_error($ch); 
            } 
            throw new Exception('Error '.$http_code.': '.$error_msg); 
        } 
 
        return $data['value']; 
    } 
 
    public function GetCalendarsList($access_token) { 
        $url_parameters = array(); 
 
        $url_parameters['fields'] = 'items(id,summary,timeZone)'; 
        $url_parameters['minAccessRole'] = 'owner'; 
 
        $url_calendars self::CALENDAR_LIST.'?'http_build_query($url_parameters); 
         
        $ch curl_init();         
        curl_setopt($chCURLOPT_URL$url_calendars);         
        curl_setopt($chCURLOPT_RETURNTRANSFER1);     
        curl_setopt($chCURLOPT_HTTPHEADER, array('Authorization: Bearer '$access_token));     
        curl_setopt($chCURLOPT_SSL_VERIFYPEERFALSE);     
        $data json_decode(curl_exec($ch), true); 
        $http_code curl_getinfo($ch,CURLINFO_HTTP_CODE); 
         
        if ($http_code != 200) { 
            $error_msg 'Failed to get calendars list'; 
            if (curl_errno($ch)) { 
                $error_msg curl_error($ch); 
            } 
            throw new Exception('Error '.$http_code.': '.$error_msg); 
        } 
 
        return $data['items']; 
    } 
 
    public function CreateCalendarEvent($access_token$calendar_id$event_data$all_day$event_datetime$event_timezone) { 
        $apiURL self::CALENDAR_EVENT $calendar_id '/events'; 
         
        $curlPost = array(); 
         
        if(!empty($event_data['summary'])){ 
            $curlPost['summary'] = $event_data['summary']; 
        } 
         
        if(!empty($event_data['location'])){ 
            $curlPost['location'] = $event_data['location']; 
        } 
         
        if(!empty($event_data['description'])){ 
            $curlPost['description'] = $event_data['description']; 
        } 
         
        $event_date = !empty($event_datetime['event_date'])?$event_datetime['event_date']:date("Y-m-d"); 
        $start_time = !empty($event_datetime['start_time'])?$event_datetime['start_time']:date("H:i:s"); 
        $end_time = !empty($event_datetime['end_time'])?$event_datetime['end_time']:date("H:i:s"); 
 
        if($all_day == 1){ 
            $curlPost['start'] = array('date' => $event_date); 
            $curlPost['end'] = array('date' => $event_date); 
        }else{ 
            $timezone_offset $this->getTimezoneOffset($event_timezone); 
            $timezone_offset = !empty($timezone_offset)?$timezone_offset:'07:00'; 
            $dateTime_start $event_date.'T'.$start_time.$timezone_offset; 
            $dateTime_end $event_date.'T'.$end_time.$timezone_offset; 
             
            $curlPost['start'] = array('dateTime' => $dateTime_start'timeZone' => $event_timezone); 
            $curlPost['end'] = array('dateTime' => $dateTime_end'timeZone' => $event_timezone); 
        } 
        $ch curl_init();         
        curl_setopt($chCURLOPT_URL$apiURL);         
        curl_setopt($chCURLOPT_RETURNTRANSFER1);         
        curl_setopt($chCURLOPT_POST1);         
        curl_setopt($chCURLOPT_SSL_VERIFYPEERFALSE); 
        curl_setopt($chCURLOPT_HTTPHEADER, array('Authorization: Bearer '$access_token'Content-Type: application/json'));     
        curl_setopt($chCURLOPT_POSTFIELDSjson_encode($curlPost));     
        $data json_decode(curl_exec($ch), true); 
        $http_code curl_getinfo($ch,CURLINFO_HTTP_CODE);         
         
        if ($http_code != 200) { 
            $error_msg 'Failed to create event'; 
            if (curl_errno($ch)) { 
                $error_msg curl_error($ch); 
            } 
            throw new Exception('Error '.$http_code.': '.$error_msg); 
        } 
 
        return $data['id']; 
    } 
     
    private function getTimezoneOffset($timezone 'America/Los_Angeles'){ 
        $current   timezone_open($timezone); 
        $utcTime  = new \DateTime('now', new \DateTimeZone('UTC')); 
        $offsetInSecs =  timezone_offset_get($current$utcTime); 
        $hoursAndSec gmdate('H:i'abs($offsetInSecs)); 
        return stripos($offsetInSecs'-') === false "+{$hoursAndSec}"-{$hoursAndSec}"; 
    } 
} 
?>

 

 

Database and API Configuration (config.php)

 

Database settings and Google API setup constant variables are defined in the config.php file.

 

Constants in the database:

 

- DB HOST – The database hostname.

- DB USERNAME – Enter the database username here.

- DB PASSWORD – Enter the database password here.

- DB NAME – Enter the name of the database.

 

Constants in the Google API:

 

- GOOGLE CLIENT ID – The Google Project Client ID must be specified.

- GOOGLE CLIENT SECRET – Enter the Google Project Client Secret here.

- GOOGLE OAUTH SCOPE – Set the OAuth scope for Google authentication (https://www.googleapis.com/auth/calendar).

- REDIRECT URI – Enter the Callback URL here.

 

OAuth URL for Google:

 

-  $googleOauthURL – The URL used to authenticate the user with their Google account.

// Database configuration    
define('DB_HOST''MySQL_Database_Host'); 
define('DB_USERNAME''MySQL_Database_Username'); 
define('DB_PASSWORD''MySQL_Database_Password'); 
define('DB_NAME''MySQL_Database_Name'); 
 
// Google API configuration 
define('GOOGLE_CLIENT_ID''Google_Project_Client_ID'); 
define('GOOGLE_CLIENT_SECRET''Google_Project_Client_Secret'); 
define('GOOGLE_OAUTH_SCOPE''https://www.googleapis.com/auth/calendar'); 
define('REDIRECT_URI''https://www.example.com/google_calendar_event_sync.php'); 
 
// Start session 
if(!session_id()) session_start(); 
 
// Google OAuth URL 
$googleOauthURL 'https://accounts.google.com/o/oauth2/auth?scope=' urlencode(GOOGLE_OAUTH_SCOPE) . '&redirect_uri=' REDIRECT_URI '&response_type=code&client_id=' GOOGLE_CLIENT_ID '&access_type=online'; 
 
?>

 

 

 

Database Connection (dbConfig.php)

 

The dbConfig.php file is used by PHP to connect to and choose the MySQL database.

// Include configuration file 
require_once 'config.php'; 
 
// Create database connection 
$db = new mysqli(DB_HOSTDB_USERNAMEDB_PASSWORDDB_NAME); 
 
// Check connection 
if ($db->connect_error) { 
    die("Connection failed: " $db->connect_error); 
}

 

 

Event Creation Form (index.php)

 

Make an HTML form to collect event information (title, description, location, date, and time). When you submit the form, the event data is sent to the server-side script (addEvent.php) for processing.

// Include configuration file 
include_once 'config.php'; 
 
$postData ''; 
if(!empty($_SESSION['postData'])){ 
    $postData $_SESSION['postData']; 
    unset($_SESSION['postData']); 
} 
 
$status $statusMsg ''; 
if(!empty($_SESSION['status_response'])){ 
    $status_response $_SESSION['status_response']; 
    $status $status_response['status']; 
    $statusMsg $status_response['status_msg']; 
} 
?>


if(!empty($statusMsg)){ ?>
    <div class="alert alert-echo $status?>">echo $statusMsg?>div>
?>

<div class="col-md-12">
    <form method="post" action="addEvent.php" class="form">
        <div class="form-group">
            <label>Event Titlelabel>
            <input type="text" class="form-control" name="title" value="echo !empty($postData['title'])?$postData['title']:''?>" required="">
        div>
        <div class="form-group">
            <label>Event Descriptionlabel>
            <textarea name="description" class="form-control">echo !empty($postData['description'])?$postData['description']:''?>textarea>
        div>
        <div class="form-group">
            <label>Locationlabel>
            <input type="text" name="location" class="form-control" value="echo !empty($postData['location'])?$postData['location']:''?>">
        div>
        <div class="form-group">
            <label>Datelabel>
            <input type="date" name="date" class="form-control" value="echo !empty($postData['date'])?$postData['date']:''?>" required="">
        div>
        <div class="form-group time">
            <label>Timelabel>
            <input type="time" name="time_from" class="form-control" value="echo !empty($postData['time_from'])?$postData['time_from']:''?>">
            <span>TOspan>
            <input type="time" name="time_to" class="form-control" value="echo !empty($postData['time_to'])?$postData['time_to']:''?>">
        div>
        <div class="form-group">
            <input type="submit" class="form-control btn-primary" name="submit" value="Add Event"/>
        div>
    form>
div>

 

 

Add an Event to Database (addEvent.php)

 

The addEvent.php file is in charge of inserting event data into the MySQL database.

 

- Using the PHP $_POST variable, retrieve event information from the user's input.

 

- Validate input to ensure that no necessary fields are left blank.

 

- Using PHP and MySQL, insert event data into the database.

 

- Redirect the user to the OAuth URL for Google account authentication.

 

// Include database configuration file 
require_once 'dbConfig.php'; 
 
$postData $statusMsg $valErr ''; 
$status 'danger'; 
 
// If the form is submitted 
if(isset($_POST['submit'])){ 
     
    // Get event info 
    $_SESSION['postData'] = $_POST; 
    $title = !empty($_POST['title'])?trim($_POST['title']):''; 
    $description = !empty($_POST['description'])?trim($_POST['description']):''; 
    $location = !empty($_POST['location'])?trim($_POST['location']):''; 
    $date = !empty($_POST['date'])?trim($_POST['date']):''; 
    $time_from = !empty($_POST['time_from'])?trim($_POST['time_from']):''; 
    $time_to = !empty($_POST['time_to'])?trim($_POST['time_to']):''; 
     
    // Validate form input fields 
    if(empty($title)){ 
        $valErr .= 'Please enter event title.
'; 
    } 
    if(empty($date)){ 
        $valErr .= 'Please enter event date.
'; 
    } 
     
    // Check whether user inputs are empty 
    if(empty($valErr)){ 
        // Insert data into the database 
        $sqlQ "INSERT INTO events (title,description,location,date,time_from,time_to,created) VALUES (?,?,?,?,?,?,NOW())"; 
        $stmt $db->prepare($sqlQ); 
        $stmt->bind_param("ssssss"$db_title$db_description$db_location$db_date$db_time_from$db_time_to); 
        $db_title $title; 
        $db_description $description; 
        $db_location $location; 
        $db_date $date; 
        $db_time_from $time_from; 
        $db_time_to $time_to; 
        $insert $stmt->execute(); 
         
        if($insert){ 
            $event_id $stmt->insert_id; 
             
            unset($_SESSION['postData']); 
             
            // Store event ID in session 
            $_SESSION['last_event_id'] = $event_id; 
             
            header("Location: $googleOauthURL"); 
            exit(); 
        }else{ 
            $statusMsg 'Something went wrong, please try again after some time.'; 
        } 
    }else{ 
        $statusMsg '

Please fill all the mandatory fields:

'.trim($valErr'
'
);     } }else{     $statusMsg 'Form submission failed!'; } $_SESSION['status_response'] = array('status' => $status'status_msg' => $statusMsg); header("Location: index.php"); exit(); ?>

 

 

Add Event to Google Calendar (google_calendar_event_sync.php)

 

 

In the Google API settings, this script is configured as the Redirect URI. This implies that after logging in with their Google account, the user will be forwarded to this script, which handles the Google Calendar event creation procedure with PHP.

 

- Using the PHP $_GET variable, extract the OAuth code from the URL's query string.

 

- Include the Google Calendar API handler class and initialise it.

 

- SESSION returns the event reference ID for the local database.

 

- Using the reference ID, retrieve the event information from the database.

 

- Prepare event data for Google Calendar (summary, description, location, date, start time, and finish time).

 

- Obtain an access token by using the GetAccessToken() method of the GoogleCalendarApi class.

 

- The GetUserCalendarTimezone() method of the GoogleCalendarApi class is used to retrieve the user's timezone from Google calendar settings.

 

- Using the GoogleCalendarApi class's CreateCalendarEvent() method, create an event and add it to Google Calendar.

 

- In the database, update the Google event reference.

 

- Display the status of an event's creation along with a link to Google Calendar.

 

// Include Google calendar api handler class 
include_once 'GoogleCalendarApi.class.php'; 
     
// Include database configuration file 
require_once 'dbConfig.php'; 
 
$statusMsg ''; 
$status 'danger'; 
if(isset($_GET['code'])){ 
    // Initialize Google Calendar API class 
    $GoogleCalendarApi = new GoogleCalendarApi(); 
     
    // Get event ID from session 
    $event_id $_SESSION['last_event_id']; 
 
    if(!empty($event_id)){ 
         
        // Fetch event details from database 
        $sqlQ "SELECT * FROM events WHERE id = ?"; 
        $stmt $db->prepare($sqlQ);  
        $stmt->bind_param("i"$db_event_id); 
        $db_event_id $event_id; 
        $stmt->execute(); 
        $result $stmt->get_result(); 
        $eventData $result->fetch_assoc(); 
         
        if(!empty($eventData)){ 
            $calendar_event = array( 
                'summary' => $eventData['title'], 
                'location' => $eventData['location'], 
                'description' => $eventData['description'] 
            ); 
             
            $event_datetime = array( 
                'event_date' => $eventData['date'], 
                'start_time' => $eventData['time_from'], 
                'end_time' => $eventData['time_to'] 
            ); 
             
            // Get the access token 
            $access_token_sess $_SESSION['google_access_token']; 
            if(!empty($access_token_sess)){ 
                $access_token $access_token_sess; 
            }else{ 
                $data $GoogleCalendarApi->GetAccessToken(GOOGLE_CLIENT_IDREDIRECT_URIGOOGLE_CLIENT_SECRET$_GET['code']); 
                $access_token $data['access_token']; 
                $_SESSION['google_access_token'] = $access_token; 
            } 
             
            if(!empty($access_token)){ 
                try { 
                    // Get the user's calendar timezone 
                    $user_timezone $GoogleCalendarApi->GetUserCalendarTimezone($access_token); 
                 
                    // Create an event on the primary calendar 
                    $google_event_id $GoogleCalendarApi->CreateCalendarEvent($access_token'primary'$calendar_event0$event_datetime$user_timezone); 
                     
                    //echo json_encode([ 'event_id' => $event_id ]); 
                     
                    if($google_event_id){ 
                        // Update google event reference in the database 
                        $sqlQ "UPDATE events SET google_calendar_event_id=? WHERE id=?"; 
                        $stmt $db->prepare($sqlQ); 
                        $stmt->bind_param("si"$db_google_event_id$db_event_id); 
                        $db_google_event_id $google_event_id; 
                        $db_event_id $event_id; 
                        $update $stmt->execute(); 
                         
                        unset($_SESSION['last_event_id']); 
                        unset($_SESSION['google_access_token']); 
                         
                        $status 'success'; 
                        $statusMsg '

Event #'.$event_id.' has been added to Google Calendar successfully!

';                         $statusMsg .= '

Open Calendar';                     }                 } catch(Exception $e) {                     //header('Bad Request', true, 400);                     //echo json_encode(array( 'error' => 1, 'message' => $e->getMessage() ));                     $statusMsg $e->getMessage();                 }             }else{                 $statusMsg 'Failed to fetch access token!';             }         }else{             $statusMsg 'Event data not found!';         }     }else{         $statusMsg 'Event reference not found!';     }          $_SESSION['status_response'] = array('status' => $status'status_msg' => $statusMsg);          header("Location: index.php");     exit(); } ?>

 

 

Checklist for Testing

 

Google Application Verification:

 

In order to utilise the Calendar API, Google requires application verification. To make the Google project public, you must submit an application for verification.

You may test it in development mode by adding Test Users to the Google application's OAuth consent page.

 

- Click the OAuth consent screen link on the OAuth Client credentials page.

- Add people to the Test users area on the OAuth consent screen page.

 

HTTPS Protocol:

 

Google Calendar API authentication requires HTTPS. As a result, the web script's URL should be HTTPS enabled.

 

- You may test the Google Calendar API integration using HTTP on the localhost server.

 

 

Conclusion

 

Adding website events to Google Calendar is a great way to efficiently alert application users. You may sync events from your web application's event calendar to the user's Google calendar. This software allows you to dynamically add events to Google Calendar from your website using PHP. To synchronise events between the application and the user's Google calendar, the Google calendar event create capability is the ideal approach.

LICENSE OF USE

You can use it for personal or commercial projects. You can't resell it partially or in this form.

PRODUCT INFO

Create Date : Jan 17, 2022

Updated Date : Jun 30, 2022

Ratings

Comments : 0

Downloads : 0