Add an Event to Google Calendar in PHP

Google calendar is a free, cloud-based scheduling product developed and maintained by google and it is used as a tool for event managements and reminders. Learn how to add an event to google calendar in PHP using Google Calendar API to automate event management.

Add Event to Google Calendar in PHP

Google Calendar is widely used by individuals, businesses and organizations to add events and reminders for important meetings, conferences, tasks and appointments. Web developers also utilize it to streamline and automate event management processes in web applications. In this post we are going to learn how to add an event to google calendar in PHP by utilizing the google calendar API. Following files need to be created for this post

  1. index.php: The HTML page with event form.
  2. google-calendar-events.php: The server-side script code to add event to google calendar.
  3. style.css: The CSS stylesheet for event HTML page.
 

How to Add an Event to Google Calendar using Calendar API

Adding an event to google calendar requires some basic prerequisites such as enabling google calendar API, a configured google cloud project with client credentials and a google calendar to add events to. We will create a user interface with form to submit event data to server-side script, then the server-side script will make requests to google calendar API to add an event to calendar. Steps to add an event to google calendar are as below:

 

Step 1: Install Google Client API Library

We need a client library to make requests to google calendar API from our web application. So we first need to first install google client API library via composer. This library can also be downloaded as a zip archive.

composer require google/apiclient:^2.15.0
 

Step 2: Create a Cloud Console Project

Next we need to create a cloud console project to access and communicate with google services. To create a project go to Google Cloud Console and do the following:

  • Select an existing project or click on "New Project".
  • Enter a project name and click create.
Create Google Cloud Console Project

Step 3: Create and Download Service Account Credentials

In order to securely communicate with google APIs we need client credentials to make authenticated API requests to google.

  • Click "IAM and admin" from left navigation menu.
  • In sub-menu click on "Service accounts".
  • Click on "+ Create service account".
  • Enter a service account name and description if needed.
  • Click on "Done".
  • Click "Keys" tab on the create service account page.
  • Click on "Add key" and select "JSON" for Key type.
  • Click on "Create" to download a JSON key file. Save it in project directory.
Create Service Account and Download Credentials
 

Step 4: Create a Google Calendar

We also need a calendar created in google to which we will add events from our web application. We create a calendar in google and share it with google service account we created. Go to google calendar page and:

  • Click on Settings cog icon.
  • Click on "Create new calendar" under "Add calendar" in left side menu on settings page.
  • Enter calendar name and description.
  • Click on "Create Calendar" button.
  • After calendar has been created click on three vertical dots icon next to calendar name in calendars list.
  • Find the section "Shared with" and click on "Add people and groups".
  • Enter the email address of service account and click "Send".
Create Google Calendar and Share with Service Account
 

Step 5: Create an HTML Event Form

Now that we have our service account credentials and calendar created, its time to do the coding part. We will create an HTML page with form containing the fields for event details. This form will be submitted to server-side PHP script to create an event in google calendar passing the form fields as parameters. Follow these steps to create an HTML event form:

  • Start a session to display success messages.
  • Create a form with necessary fields for events.
  • We are adding fields for "calendar id", "event summary", "event location", "event description", "start time" and "end time".
  • For a complete list of event visit official calendar API page of google.

index.php

<?php
if (!session_id()) {
session_start();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Add Event to Google Calendar in PHP - Demo</title>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type"/>
<meta content="width=device-width, initial-scale=1, maximum-scale=1" name="viewport"/>
<link rel="stylesheet" href="css/style.css"/>
</head>
<body>
<section class="section py-4">
<div class="container">
<?php if (!empty($_SESSION['success'])) { ?>
<div class="alert alert-green">
Event added successfully.
</div>
<?php unset($_SESSION['success']); ?>
<?php } ?>

<div class="mb-4">
<form action="google-calendar-events.php" method="POST" class="form-google-calendar-event">
<div class="mb-4">
<label class="inline-block mb-1">Calendar ID <span class="text-red">*</span></label>
<input type="text" name="calendar_id" class="form-control" placeholder="Calendar ID..."/>
</div>
<div class="mb-4">
<label class="inline-block mb-1">Summary <span class="text-red">*</span></label>
<input type="text" name="summary" class="form-control" placeholder="Event summary..."/>
</div>
<div class="mb-4">
<label class="inline-block mb-1">Location <span class="text-red">*</span></label>
<input type="text" name="location" class="form-control" placeholder="Event location..."/>
</div>
<div class="mb-4">
<label class="inline-block mb-1">Description <span class="text-red">*</span></label>
<input type="text" name="description" class="form-control" placeholder="Event description..."/>
</div>
<div class="mb-4">
<label class="inline-block mb-1">Start <span class="text-red">*</span></label>
<input type="datetime-local" name="start" class="form-control"
placeholder="Event start date and time..."/>
</div>
<div class="mb-4">
<label class="inline-block mb-1">End <span class="text-red">*</span></label>
<input type="datetime-local" name="end" class="form-control"
placeholder="Event end date and time..."/>
</div>
<div class="mb-4">
<button type="submit" class="btn btn-blue">Add Event</button>
</div>
</form>
</div>
</div>
</section>
</body>
</html>
 

Step 6: Create an Event in Google Calendar using Calendar API (PHP)

When event form is submitted to server-side PHP script we can easily add event to google calendar using google API client library with credentials we created. Steps to add google calendar event using google client library:

  • Include the vendor autoload to use google API client library.
  • Start a session to store success messages.
  • Sanitize form post fields, you can add more filters as per your requirements.
  • Initialize google client class instance.
  • Set the config credentials of service account.
  • Assign google calendar scope of google service calendar.
  • Initialize google service calendar and assign it to google $calendar_service variable.
  • Use the form submitted values as parameters to create a google calendar event instance.
  • Add event to google calendar using $calendar_service instance.
  • Set success status in session and redirect user back to event form page.

google-calendar-events.php

<?php
include_once __DIR__ . '/vendor/autoload.php';

if (!session_id()) {
session_start();
}

$post = filter_input_array(INPUT_POST);

// Initialize google client instance
$client = new Google_Client();

// Set service account config
$client->setAuthConfig('PATH_TO_SERVICE_ACCOUNT_CREDENTIALS');

// Set google calendar scope
$client->setScopes(Google_Service_Calendar::CALENDAR);

// Initialize google calendar service
$calendar_service = new Google_Service_Calendar($client);

date_default_timezone_set('America/Los_Angeles');

$start_date_time = date('Y-m-d\TH:i:s', strtotime($post['start']));
$end_date_time = date('Y-m-d\TH:i:s', strtotime($post['end']));
$timezone_offset = date('P');

// Create google calendar event
$event = new Google_Service_Calendar_Event([
'summary' => $post['summary'],
'location' => $post['location'],
'description' => $post['description'],
'start' => ['dateTime' => sprintf('%s%s', $start_date_time, $timezone_offset)],
'end' => ['dateTime' => sprintf('%s%s', $end_date_time, $timezone_offset)],
]);

$calendar_service->events->insert($post['calendar_id'], $event);

$_SESSION['success'] = true;

// Redirect user
header('Location: ' . filter_var($_SERVER['HTTP_REFERER'], FILTER_SANITIZE_URL));
exit;
 

Step 7: Add CSS Styles

Add CSS styles for entire user interface that contains the event form.

style.css

* {
box-sizing: border-box;
}
html,body {
margin: 0;
padding: 0;
}
body {
background-color: #f6f6f6;
font-family: "Segoe UI", "Roboto", "Helvetica", sans-serif;
font-size: 15px;
font-weight: normal;
font-style: normal;
}
.container {
max-width: 1024px;
margin: 0 auto;
padding-left: 15px;
padding-right: 15px;
}
.inline-block {
display: inline-block;
}
.py-4 {
padding-top: 1rem;
padding-bottom: 1rem;
}
.my-1, .mb-1 {
margin-bottom: .25rem;
}
.my-4, .mb-4 {
margin-bottom: 1rem;
}
.alert {
position: relative;
padding: .75rem 1.25rem;
margin-bottom: 1rem;
transition:opacity 0.5s;
}
.alert-green {
background-color: #319764;
border: 1px solid #248A57;
color: #ffffff;
}
.form-control {
display: block;
width: 100%;
padding: .375rem .75rem;
font-size: 1rem;
font-weight: 400;
line-height: 1.5;
color: #1c2528;
background-color: #ffffff;
background-clip: padding-box;
border: 1px solid #d1d2d3;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
}
.btn {
display: inline-block;
padding: .375rem .75rem;
cursor: pointer;
font-size: inherit;
}
.btn-blue {
background-color: #0369a1;
border: 1px solid #0369a1;
color: #ffffff;
}
.btn-blue:hover {
background-color: #005D95;
}
 

Update Google Calendar Event in PHP

We can also update the google calendar event in PHP using client API library. We only need $calendar_id and $event_id and event parameters that we want to update for a given google calendar event. Code snippet to update a google calendar event is:

$calendar_service->events->update($post['calendar_id'], $event_id, [
'summary' => $post['summary'],
'location' => $post['location'],
'description' => $post['description'],
'start' => ['dateTime' => sprintf('%s%s', $start_date_time, $timezone_offset)],
'end' => ['dateTime' => sprintf('%s%s', $end_date_time, $timezone_offset)],
]);
 

Delete a Google Calendar Event in PHP

Just like updating an event in google calendar, we can also delete a specific event from google calendar by passing the $calendar_id and $event_id to calendar service. The code snippet to delete an event from google calendar is like this: 

$calendar_service->events->delete($post['calendar_id'], $event_id);

We demonstrates how to add, update and delete google calendar events in PHP using the google calendar API and a service account. By integrating google calendar into PHP applications, we can automate scheduling and manage events programmatically with no or less manual efforts. The code snippets in this post can also be used to add birthday to google calendar by just passing the parameter eventType = 'birthday' to event instance. Checkout additional google calendar API features google offers such as recurring events, attendees, reminders and event types to further enhance the functionality.