Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A convenient script to generate iCalendar (.ics) files on the fly in PHP.

PHP to ICS

This gist contains a convenient script to generate iCalendar (.ics) files on the fly in PHP.

Basic usage

include 'ICS.php'

$properties = array(
  'dtstart' => 'now',
  'dtend' => 'now + 30 minutes'
);

$ics = new ICS($properties);
$ics_file_contents = $ics->to_string();

Available properties

  • description - string description of the event.
  • dtend - date/time stamp designating the end of the event. You can use either a DateTime object or a PHP datetime format string (e.g. "now + 1 hour").
  • dtstart - date/time stamp designating the start of the event. You can use either a DateTime object or a PHP datetime format string (e.g. "now + 1 hour").
  • location - string address or description of the location of the event.
  • summary - string short summary of the event - usually used as the title.
  • url - string url to attach to the the event. Make sure to add the protocol (http:// or https://).

Detailed examples

Button that downloads an ICS file when clicked

This example contains a form on the front-end that submits to a PHP script that initiates a download of an ICS file. This example uses hidden form fields to set the properties dynamically.

index.html

<form method="post" action="/download-ics.php">
  <input type="hidden" name="date_start" value="2017-1-16 9:00AM">
  <input type="hidden" name="date_end" value="2017-1-16 10:00AM">
  <input type="hidden" name="location" value="123 Fake St, New York, NY">
  <input type="hidden" name="description" value="This is my description">
  <input type="hidden" name="summary" value="This is my summary">
  <input type="hidden" name="url" value="http://example.com">
  <input type="submit" value="Add to Calendar">
</form>

download-ics.php

<?php

include 'ICS.php';

header('Content-Type: text/calendar; charset=utf-8');
header('Content-Disposition: attachment; filename=invite.ics');

$ics = new ICS(array(
  'location' => $_POST['location'],
  'description' => $_POST['description'],
  'dtstart' => $_POST['date_start'],
  'dtend' => $_POST['date_end'],
  'summary' => $_POST['summary'],
  'url' => $_POST['url']
));

echo $ics->to_string();
<?php
/**
* This is free and unencumbered software released into the public domain.
*
* Anyone is free to copy, modify, publish, use, compile, sell, or
* distribute this software, either in source code form or as a compiled
* binary, for any purpose, commercial or non-commercial, and by any
* means.
*
* In jurisdictions that recognize copyright laws, the author or authors
* of this software dedicate any and all copyright interest in the
* software to the public domain. We make this dedication for the benefit
* of the public at large and to the detriment of our heirs and
* successors. We intend this dedication to be an overt act of
* relinquishment in perpetuity of all present and future rights to this
* software under copyright law.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* For more information, please refer to <http://unlicense.org>
*
* ICS.php
* =============================================================================
* Use this class to create an .ics file.
*
*
* Usage
* -----------------------------------------------------------------------------
* Basic usage - generate ics file contents (see below for available properties):
* $ics = new ICS($props);
* $ics_file_contents = $ics->to_string();
*
* Setting properties after instantiation
* $ics = new ICS();
* $ics->set('summary', 'My awesome event');
*
* You can also set multiple properties at the same time by using an array:
* $ics->set(array(
* 'dtstart' => 'now + 30 minutes',
* 'dtend' => 'now + 1 hour'
* ));
*
* Available properties
* -----------------------------------------------------------------------------
* description
* String description of the event.
* dtend
* A date/time stamp designating the end of the event. You can use either a
* DateTime object or a PHP datetime format string (e.g. "now + 1 hour").
* dtstart
* A date/time stamp designating the start of the event. You can use either a
* DateTime object or a PHP datetime format string (e.g. "now + 1 hour").
* location
* String address or description of the location of the event.
* summary
* String short summary of the event - usually used as the title.
* url
* A url to attach to the the event. Make sure to add the protocol (http://
* or https://).
*/
class ICS {
const DT_FORMAT = 'Ymd\THis\Z';
protected $properties = array();
private $available_properties = array(
'description',
'dtend',
'dtstart',
'location',
'summary',
'url'
);
public function __construct($props) {
$this->set($props);
}
public function set($key, $val = false) {
if (is_array($key)) {
foreach ($key as $k => $v) {
$this->set($k, $v);
}
} else {
if (in_array($key, $this->available_properties)) {
$this->properties[$key] = $this->sanitize_val($val, $key);
}
}
}
public function to_string() {
$rows = $this->build_props();
return implode("\r\n", $rows);
}
private function build_props() {
// Build ICS properties - add header
$ics_props = array(
'BEGIN:VCALENDAR',
'VERSION:2.0',
'PRODID:-//hacksw/handcal//NONSGML v1.0//EN',
'CALSCALE:GREGORIAN',
'BEGIN:VEVENT'
);
// Build ICS properties - add header
$props = array();
foreach($this->properties as $k => $v) {
$props[strtoupper($k . ($k === 'url' ? ';VALUE=URI' : ''))] = $v;
}
// Set some default values
$props['DTSTAMP'] = $this->format_timestamp('now');
$props['UID'] = uniqid();
// Append properties
foreach ($props as $k => $v) {
$ics_props[] = "$k:$v";
}
// Build ICS properties - add footer
$ics_props[] = 'END:VEVENT';
$ics_props[] = 'END:VCALENDAR';
return $ics_props;
}
private function sanitize_val($val, $key = false) {
switch($key) {
case 'dtend':
case 'dtstamp':
case 'dtstart':
$val = $this->format_timestamp($val);
break;
default:
$val = $this->escape_string($val);
}
return $val;
}
private function format_timestamp($timestamp) {
$dt = new DateTime($timestamp);
return $dt->format(self::DT_FORMAT);
}
private function escape_string($str) {
return preg_replace('/([\,;])/','\\\$1', $str);
}
}
@jakebellacera
Copy link
Author

jakebellacera commented Jun 20, 2019

@walesmd Thanks for the comment! I've updated the code to include a license. I chose Unlicense because what you do with the code is none of each others business. I'm just happy to help a few folks out. Enjoy 😄

@walesmd
Copy link

walesmd commented Jun 20, 2019

👍

@kristjan72
Copy link

kristjan72 commented Aug 5, 2019

Everything works except the ics file is polluted with a bunch of html code from the framework.

@mlevesque1975 I had this problem as well and exiting the script after it's done solved it for me.

Simply:
echo $ics->to_string();
exit();

@thagxt
Copy link

thagxt commented Oct 18, 2019

@phpHobbyist the Alarm option isn't activated when importing event on Mac & iOS
might be because of the lack of BEGIN:VALARM X-WR-ALARMUID: and UID:

@anandbisht
Copy link

anandbisht commented Dec 4, 2019

Is there a way to open .ics file automatically after downloading in android, if someone can help on this, that would be great

@samtigall
Copy link

samtigall commented Jan 7, 2020

Didnt work for Content lines (e.g. Description) longer than 75 characters (needs new line for correct format). See my fork for Fix.

@Bigben83
Copy link

Bigben83 commented Mar 13, 2020

I am struggling to see how to attach this file on to a mail using PHPMailer
does anyone have some clues to help ?

using the following
echo $ics->to_string();
$ics_file_contents = $ics->to_string();
$mail->addAttachment($ics_file_contents);

@ranevaibhav95
Copy link

ranevaibhav95 commented Mar 30, 2020

If anyone needs to add description which is in html format to plain text, then they need to add:

$ical = 'BEGIN:VCALENDAR
PRODID:-//Microsoft Corporation//Outlook 11.0 MIMEDIR//EN
VERSION:2.0
METHOD:PUBLISH
BEGIN:VEVENT
ORGANIZER:MAILTO:' . $event['omailid'] . '
DTSTART:' . dateToCal($event['datestart']) . '
DTEND:' . dateToCal($event['dateend']) . '
LOCATION:' . $event['location'] . '
TRANSP:OPAQUE
SEQUENCE:0
UID:' . md5($event['title']) . '
DTSTAMP:' . time() . '
DESCRIPTION:' . $event['description'] . '
X-ALT-DESC;FMTTYPE=text/html:'. $event['description'] .'

SUMMARY: ' . addslashes($event['title']) . '
PRIORITY:5
CLASS:PUBLIC
END:VEVENT
END:VCALENDAR';

@Loosie94
Copy link

Loosie94 commented May 1, 2020

Hi guys, thanks for the script. It's working great!
One question; Is there a wat to make an event repeatable for like each year?
Thanks!

@jfsiman
Copy link

jfsiman commented May 1, 2020

@kirensiva
Copy link

kirensiva commented Jun 26, 2020

Hi jakebellacera,
Thank you very much for the wonderful script. I am trying to send an event as an email like in outlook. I created a ics file for this. But problem is that outlook is not treating this mail as an event but it is treating like a normal email with attachment (.ics). Do you have any idea why this is happening?

@samisaacscreative
Copy link

samisaacscreative commented Sep 23, 2020

I am struggling to see how to attach this file on to a mail using PHPMailer
does anyone have some clues to help ?

using the following
echo $ics->to_string();
$ics_file_contents = $ics->to_string();
$mail->addAttachment($ics_file_contents);

@Bigben83 - this worked for me:
include 'ICS.php';

$ics = new ICS(array(
'location' => $location,
'description' => $mdesc,
'dtstart' => $sdate,
'dtend' => $edate,
'summary' => $mname,
'url' => $meetURL
));

$ical = $ics->to_string();

$mail->AddStringAttachment("$ical", "filename.ics", "base64", "text/calendar; charset=utf-8; method=REQUEST");

Make sure you remove the two headers before trying this! The vars in the array are for a pass through from a form.

@samisaacscreative
Copy link

samisaacscreative commented Sep 23, 2020

Thank you so much @jakebellacera - works like a charm!

Sam.

@semihagursoy
Copy link

semihagursoy commented Dec 4, 2020

Hi @jakebellacera thank you so much! What you've created is amazing.
Just a quick question, I've been searching for other ways to output the data without using echo or print. Is it possible? and if yes, how can I do it?

@lhuria94
Copy link

lhuria94 commented Dec 10, 2020

Hi guys, any one been able to generate the ics file with organizer?
I have been trying, it comes as part of file but while importing there is no organizer.

@samcollett-bms
Copy link

samcollett-bms commented Dec 17, 2020

Just been using this and I had to add on the dateToCal function, strtotime.

The code should look something like this:
function dateToCal($time) { return date('Ymd\This', strtotime($time)) . 'Z'; }

I have tried it without this and every time, the year is displaying at 1970.

@vincentwansink
Copy link

vincentwansink commented Mar 16, 2021

To fix the timezone issue just make this simple change to the ics.php file: (I bolded the changes)

public function to_string($timezone) {
$rows = $this->build_props($timezone);
return implode("\r\n", $rows);
}

private function build_props($timezone) {
// Build ICS properties - add header
$ics_props = array(
'BEGIN:VCALENDAR',
'VERSION:2.0',
'PRODID:-//hacksw/handcal//NONSGML v1.0//EN',
'CALSCALE:GREGORIAN',
'X-WR-TIMEZONE:$timezone',
'BEGIN:VEVENT'
);

Then when you call to_string() in your ics download file, just pass in the timezone string (for example 'America/Denver').

Like this:

echo $ics->to_string('America/Denver');

@Emgeth
Copy link

Emgeth commented Apr 28, 2021

Hi
You code is great. However, when I try to use it on my professional website to generate a ICS file, it appears coded as ANSI and not UTF-8 although I did copy the header Content-Type. Would you know why it is so ? When I copy the content of the file to a notepad file newly open, it is recognized as UTF-8 coded and I can import the file under Thunderbird... For a reason I don't undertsand the download-ics.php file does do the job correctly. Would you know why it is so ?
Thanks

@abhishek-kesharwani
Copy link

abhishek-kesharwani commented Jun 2, 2021

Hi,
can anyone plz help me.
what should be the content of ICS file for UTC TimeZone

@StefanoBavota
Copy link

StefanoBavota commented Jun 5, 2021

i have a db with multiple events how can i add all in one file .ics?

@manish-techlect
Copy link

manish-techlect commented Jun 9, 2021

instead of creating a file, can we buffer the file and send as an attachment in the email?

@semihagursoy-mc
Copy link

semihagursoy-mc commented Jun 14, 2021

i have a db with multiple events how can i add all in one file .ics?

Hi,
I was creating a software with the same requirements, I had to create an ics file which includes multiple events. You need to add all the events to your code, what I did was to create a foreach loop which includes this:

BEGIN:VCALENDAR
VERSION:2.0
METHOD:PUBLISH
BEGIN:VEVENT
DTSTART: --COMES FROM THE DB, CONVERT IT--
DTEND:  --COMES FROM THE DB, CONVERT IT--
LOCATION: COMES FROM THE DB
TRANSP: OPAQUE
SEQUENCE:0
UID:
DTSTAMP:   --COMES FROM THE DB, CONVERT IT--
SUMMARY: COMES FROM THE DB
DESCRIPTION: COMES FROM THE DB
PRIORITY:1
CLASS:PUBLIC
BEGIN:VALARM
TRIGGER:-PT10080M
ACTION:DISPLAY
DESCRIPTION:Reminder
End:VALARM
End:VEVENT
End:VCALENDAR

Those parts I commented as "comes from the db" fill them with the info you wish to show in the ics file and make sure that the code in the file has the same structure as above. If there is not a line break, the ics file will not be opened. I hope this helps.

@SteinbockApplications
Copy link

SteinbockApplications commented Jun 17, 2021

Update the following function format_timestamp in ICS.php, to include a timestamp change to UTC on line 2:

  private function format_timestamp($timestamp) {
    $dt = new DateTime($timestamp);
    $dt->setTimezone(new DateTimeZone('UTC'));
    return $dt->format(self::DT_FORMAT);
  }

@youngrichu
Copy link

youngrichu commented Jun 22, 2021

I get "Forms are disabled in Gmail"

@mkormendy
Copy link

mkormendy commented Jul 17, 2021

EDIT: as @MacTEC has pointed out, H is the correct representation for 24-hour time. I have updated the gist with that.

Hrmm, I'm not seeing the update.

@dansleboby
Copy link

dansleboby commented Oct 18, 2021

@biagioboi
Copy link

biagioboi commented Nov 5, 2021

If you have issues with timezone please modify line 150 in ICS.php by adding the correct TimeZone to constructor, for example for Rome:

$dt = new DateTime($timestamp, new DateTimeZone('Europe/Rome'));

@Thomas-Do
Copy link

Thomas-Do commented Dec 15, 2021

To enter your dates and times with local timezone and export in UTC
replace line 150
$dt = new DateTime($timestamp);
by
$dt = new DateTime($timestamp, new DateTimeZone(date_default_timezone_get()));
$dt->setTimeZone(new DateTimeZone('UTC'));

When importing these ics files in calendars the correct local time is recognized.

@ImpendSB
Copy link

ImpendSB commented Mar 14, 2022

Curious if anyone knows how to save ics file to a different directory vs 'downloads' ?
Much appreciated.

@loddyb
Copy link

loddyb commented Jul 15, 2022

Everything works except the ics file is polluted with a bunch of html code from the framework.

@mlevesque1975 I had this problem as well and exiting the script after it's done solved it for me.

Simply: echo $ics->to_string(); exit();

I am also having this issue. Adding the exit(); didn't fix it for me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment