🔔 WebPush Example

The following page shows how the WebPush library works.

📅 Last updated: 2025-05-22

📁 Download the files

First, download the library file .webpushclass.php (This file should not be publicly available).
Also download the project directory webpush/, which contains 3 files (This directory has to be publicly available):

📝 Customize webpush.php

Now you need to change the webpush.php file.
In order for you to be able to address your users individually, you need to create some code to save the id of the subscription to the corresponding user.
Keep in mind, that a user could subscribe with multiple devices!

PS: If you are sure you will only broadcast notifications, simply return TRUE for both functions.

<?php
    // Include the library
    require __dir__ . '/path_to_webpushclass_file_relative_to_this_file/.webpushclass.php';
    
    // Extend the class
    class WebPush extends WebPushClass {
        protected function subscribeCallback(int $id) : bool {
            // Your code to save the subscription ID to a specific user
            // Keep in mind that a user could subscribe with multiple devices!
            
            E.g.: Save $id to database where $_SESSION['userID']
                  Return if the user is allowed to do so
        }
        
        protected function unsubscribeCallback(int $id) : bool {
            // Your code to remove the subscription ID from a specific user
            
            E.g.: Remove ID from database where $id and $_SESSION['userID']
                  Return if the user is allowed to do so
        }
    }
    
    // Create a new instance of the class
    // This is needed for the subscription and desubscription to work!
    $webPush = new WebPush();
?>

📋 Other requirements

Use the library

📲 JavaScript - enabling/disabling Notifications

You can use the function subscribeWebPush() : Promise.then(bool isNew).catch(bool|string error) to automatically ask for permission to send notifications if not yet given and calls the PHP-callback subscribeCallback if the user subscribed.

If the error is a string, it may contain one of the following values other than "granted":
https://developer.mozilla.org/en-US/docs/Web/API/Notification/requestPermission_static#return_value.

subscribeWebPush()
    .then((isNew) => {
        // Alert the user that the subscription worked
        
        alert(isNew ? "Newly subscribed!" : "Already subscribed.");
    })
    .catch((error) => {
        // Alert the user that an error happened
        // error contains the notification permission if its not "allowed"
        
        alert((error === false) ? "Error" : "Notification permission not allowed : " + error);
    });

To unsubscribe a user, you can use the function unsubscribeWebPush() : Promise.then().catch(). This doesn't revoke notification permissions (this makes re-subscribing easier for the user), but calls the PHP-callback unsubscribeCallback for you to remove the subscription-ID from the user.

unsubscribeWebPush()
    .then(() => {
        // Alert the user that the desubscription worked
        
        alert("Desubscribed!");
    })
    .catch(() => {
        // Alert the user that the desubscription failed
        
        alert("Error");
    });

📨 PHP - sending Notifications

Now wherever you need to send a notification, you can use the function sendNotification(?int $id, string $title, array $options) : bool.
This function returns TRUE if all notifications were sent successfully (this doesnt mean that they were received successfully!) or FALSE if one or more notifications failed.

PS: For broadcasting, use NULL for the $id field.

<?php
    // Include your class
    require 'path_to_project_folder/webpush.php';
    
    $subscriptionID = E.g.: Get ID from database where $_SESSION['userID'];
    
    /*
        Send a notification:
        
        1st param:  NULL to notify everyone OR
                    an ID saved in the subscribeCallback
        2nd param:  The title of the notification                   (https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration/showNotification#title)
        3rd param:  The options of the notification                 (https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration/showNotification#options)
    */
    $webPush->sendNotification($subscriptionID, "Example Title", [ "body" => "Hello World!" ]);
?>

🔔 Example