Thursday 1 February 2024

Create .ICS file using PHP code

Recently worked on creating a .ics file in PHP after a very long time, code so thought to share with everybody.

Please find below the complete code and modify it as per your need. 

Once the .ics file is generated, you can open it in Outlook and Save it.

<?php

class ICS {
    var $data;
    var $name;
    function ICS($start,$end,$name,$description,$location) {
        $this->name = $name;
        $this->data = "BEGIN:VCALENDAR\nVERSION:2.0\nMETHOD:PUBLISH\nBEGIN:VEVENT
        \nDTSTART:".date("Ymd\THis\Z",strtotime($start)).
        "\nDTEND:".date("Ymd\THis\Z",strtotime($end))."\nLOCATION:".$location."
        \nTRANSP: OPAQUE\nSEQUENCE:0\nUID:\nDTSTAMP:"
        .date("Ymd\THis\Z")."\nSUMMARY:".$name."\nDESCRIPTION:".
        $description."\nPRIORITY:1\nCLASS:PUBLIC\nBEGIN:VALARM\nTRIGGER:-PT10080M
        \nACTION:DISPLAY\nDESCRIPTION:Reminder\nEND:VALARM\nEND:VEVENT\nEND:VCALENDAR
        \n";
    }
    function save() {
        file_put_contents($this->name.".ics",$this->data);
    }
    function show() {
        header("Content-type:text/calendar");
        header('Content-Disposition: attachment;
        filename="'.$this->name.'.ics"');
        Header('Content-Length: '.strlen($this->data));
        Header('Connection: close');
        echo $this->data;
    }
}

$event = new ICS("2024-02-06 09:00","2024-02-06 21:00",
"Test Event", "This is an event made by Test User","Test Location");
$event->save();
$event->show();

Create .ICS file using PHP code

Recently worked on creating a .ics file in PHP after a very long time, code so thought to share with everybody. Please find below the comple...