PHP Classes

PHP Web Push Notifications Server: Queue and push notifications to Web users

Recommend this page to a friend!
     
  Info   Example   View files Files   Install with Composer Install with Composer   Download Download   Reputation   Support forum   Blog    
Ratings Unique User Downloads Download Rankings
StarStarStarStar 79%Total: 2,112 All time: 1,852 This week: 43Up
Version License PHP version Categories
pnserver 1.2.0Freely Distributable7.4Web services, PHP 7
Description 

Author

This package can queue and push notifications to Web users.

It can register the interest of users to receive notifications from the server by creating user subscriptions.

The package provides means to queue notification messages to be sent to users of an application by storing them in a database.

Then it can return queued messages, so they can be shown to Web uses on a Web page using custom JavaScript code that pulls the messages from the server using this package.

The package can also automatically delete expired messages and no longer valid subscriptions.

Innovation Award
PHP Programming Innovation award winner
April 2020
Winner
Web based push notifications are useful to let users of a site know about anything new that happens on a site that may be of the interest of those users.

This package provides a complete solution to register users interested to subscribe to get notifications from a site, queue notifications to be pushed to the users when they come to the site, and even perform maintenance on the notifications and subscriptions created by the users.

Manuel Lemos
Picture of Stefan Kientzler
  Performance   Level  
Innovation award
Innovation award
Nominee: 11x

Winner: 6x

 

Recommendations

Push notifications for web browsers and now Apple iOS 16.4 pwa
I can’t find any packages that are current and work for webpush

Example

<?php
require_once 'autoloader.php';
require_once
'MyVapid.php';
require_once
'MyLogger.php';

use
SKien\PNServer\PNDataProviderSQLite;
use
SKien\PNServer\PNPayload;
use
SKien\PNServer\PNServer;
use
SKien\PNServer\PNSubscription;

/**
 * Example to send your push notifications.
 *
 * For easy setup we use the SQLite dataprovider and set the database file
 * located in the same directory as this script.
 *
 * First you should open PNTestClient.html in your browser and click the
 * [Subscribe] button to create a valis subscription in your database.
 *
 * Needed steps to send notification to all subscriptions stored in our database:
 * 1. Create and init dataprovider for database containing at least one valid subscription
 * 2. Set our VAPID keys (rename MyVapid.php.org to MyVapid.php ans set your own keys)
 * 3. Create and set the payload
 * 4. Load the subscriptions from the dataprovider
 * 5. And push the notification
 *
 * After the notification was pushed, a summary and/or a detailed log can be
 * retrieved from the server
 *
 * If you want to log several events or errors, you can pass any PSR-3 compliant
 * logger of your choice to the PNDataProvider- and PNServer-object.
 *
 * THIS CODE IS INTENDED ONLY AS EXAMPLE - DONT USE IT DIRECT IN YOU PROJECT
 *
 * @author Stefanius <s.kientzler@online.de>
 * @copyright MIT License - see the LICENSE file for details
 */

// check, if PHP version is sufficient and all required extensions are installed
$bExit = false;
if (
version_compare(phpversion(), '7.4', '<')) {
   
trigger_error('At least PHP Version 7.4 is required (current Version is ' . phpversion() . ')!', E_USER_WARNING);
   
$bExit = true;
}
$aExt = array('curl', 'gmp', 'mbstring', 'openssl', 'bcmath');
foreach (
$aExt as $strExt) {
    if (!
extension_loaded($strExt)) {
       
trigger_error('Extension ' . $strExt . ' must be installed!', E_USER_WARNING);
       
$bExit = true;
    }
}
if (
$bExit) {
    exit();
}

// for this test we use SQLite database
$logger = createLogger();
$oDP = new PNDataProviderSQLite(null, null, null, $logger);
if (!
$oDP->isConnected()) {
    echo
$oDP->getError();
    exit();
}

echo
'Count of subscriptions: ' . $oDP->count() . '<br/><br/>' . PHP_EOL;
if (!
$oDP->init()) {
    echo
$oDP->getError();
    exit();
}

// the server to handle all
$oServer = new PNServer($oDP);
$oServer->setLogger($logger);

// Set our VAPID keys
$oServer->setVapid(getMyVapid());

// create and set payload
// - we don't set a title - so service worker uses default
// - URL to icon can be
// * relative to the origin location of the service worker
// * absolute from the homepage (begining with a '/')
// * complete URL (beginning with https://)
$oPayload = new PNPayload('', "...first text to display.", './elephpant.png');
$oPayload->setTag('news', true);
$oPayload->setURL('/where-to-go.php');

$oServer->setPayload($oPayload);

// load subscriptions from database
if (!$oServer->loadSubscriptions()) {
    echo
$oDP->getError();
    exit();
}

// ... and finally push !
if (!$oServer->push()) {
    echo
'<h2>' . $oServer->getError() . '</h2>' . PHP_EOL;
} else {
   
$aLog = $oServer->getLog();
    echo
'<h2>Summary:</h2>' . PHP_EOL;
   
$summary = $oServer->getSummary();
    echo
'total:&nbsp;' . $summary['total'] . '<br/>' . PHP_EOL;
    echo
'pushed:&nbsp;' . $summary['pushed'] . '<br/>' . PHP_EOL;
    echo
'failed:&nbsp;' . $summary['failed'] . '<br/>' . PHP_EOL;
    echo
'expired:&nbsp;' . $summary['expired'] . '<br/>' . PHP_EOL;
    echo
'removed:&nbsp;' . $summary['removed'] . '<br/>' . PHP_EOL;

    echo
'<h2>Push - Log:</h2>' . PHP_EOL;
    foreach (
$aLog as $strEndpoint => $aMsg ) {
        echo
PNSubscription::getOrigin($strEndpoint) . ':&nbsp;' .$aMsg['msg'] . '<br/>' . PHP_EOL;
    }
}


Details

PNServer - Web Push Notifications for your Homepage

Latest Stable Version License Donate Minimum PHP Version PHPStan Scrutinizer Code Quality codecov

With this package, web push notifications can be created, encrypted and sent via HTTP request. The subscriptions can be saved and managed. Optionally, the package automatically deletes expired or no longer valid subscriptions. The JavaScript code required on the client side is also included in the package - this has to be slightly adapted to your own project.

> Important: > > The client side of this package works with the Javascript Notification API, which is only available in a secure context (HTTPS). Thus, the complete package also depends on running in a secure context (also in the test environment - unless both the server and the client run on the *'localhost'*). > > Here you can read more about how to set up a secure context in the local development environment.

required PHP Libraries

  • cURL (curl)
  • Multibyte String (mbstring)
  • OpenSSL (openssl)
  • GNU Multiple Precision (gmp)
  • BC Math (bcmath)

there are no dependencies to other external libraries!

Installation

You can download the Latest release version from PHPClasses.org

required adaptions for your own project (in PNServiceworker.js):

  // VAPID appPublic key
  const strAppPublicKey   = 'create your own VAPID key pair and insert public key here';
  // URL to save subscription on server via Fetch API
  const strSubscriberURL  = 'https://www.your-domain.org/PNSubscriber.php';
  // default Notification Title if not pushed by server
  const strDefTitle       = 'Your company or product';
  // default Notification Icon if not pushed by server
  const strDefIcon        = './elephpant.png';

There are several websites where you can generate your own VAPID key. E.g.:

Usage

A tutorial describing the individual steps for using the package is available at PHPclasses.org.

PnTestClient.html shows a simple example Page to subscribe the push notifications.

PNTestServer.php demonstrates, how the Notification Server can be implemented:

rename MyVapid.php.org to MyVapid.php and set your own keys:

  $oVapid = new PNVapid(
      "mailto:yourmail@yourdomain.de",
      "your-generated-public-key",
      "your-generated-private-key"
  );

Logging

This package can use any PSR-3 compliant logger. The logger is initialized with a NullLogger-object by default. The logger of your choice have to be passed to the constructor of the PNDataProvider and set via setLogger() method to the PNServer.

If you are not working with a PSR-3 compatible logger so far, this is a good opportunity to deal with this recommendation and may work with it in the future.

There are several more or less extensive PSR-3 packages available on the Internet.

You can also take a look at the 'XLogger' package and the associated blog 'PSR-3 logging in a PHP application' as an introduction to this topic.


  Files folder image Files (54)  
File Role Description
Files folder imagePsr (1 directory)
Files folder imageSKien (2 directories)
Accessible without login Plain text file autoloader.php Aux. Auxiliary script
Accessible without login Image file elephpant.png Icon Icon image
Accessible without login Plain text file LICENSE Lic. License text
Accessible without login Plain text file MyLogger.php Example Example script
Accessible without login Plain text file MyVapid.php.org Example Example script
Accessible without login Plain text file phpstan.neon Data Auxiliary data
Accessible without login Plain text file phpunit.xml.org Data Auxiliary data
Accessible without login Plain text file PNClient.js Data Auxiliary data
Accessible without login Plain text file PNSendWelcome.php Example Example script
Accessible without login Plain text file PNServiceWorker.js Data Auxiliary data
Accessible without login Plain text file PNSubscriber.php Example Example script
Accessible without login Plain text file PNTestClient.html Data Example HTML page client
Accessible without login Plain text file PNTestPushSingle.php Example Example script
Accessible without login Plain text file PNTestServer.php Example Example script
Accessible without login Plain text file readme.md Doc. Documentation

The PHP Classes site has supported package installation using the Composer tool since 2013, as you may verify by reading this instructions page.
Install with Composer Install with Composer
 Version Control Unique User Downloads Download Rankings  
 100%
Total:2,112
This week:0
All time:1,852
This week:43Up
User Ratings User Comments (2)
 All time
Utility:100%StarStarStarStarStarStar
Consistency:100%StarStarStarStarStarStar
Documentation:96%StarStarStarStarStar
Examples:100%StarStarStarStarStarStar
Tests:-
Videos:-
Overall:79%StarStarStarStar
Rank:25