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,100 This week: 1All time: 1,863 This week: 34Up
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  
Name: Stefan Kientzler is available for providing paid consulting. Contact Stefan Kientzler .
Classes: 19 packages by
Country: Germany Germany
Age: 57
All time rank: 71946 in Germany Germany
Week rank: 44 Up2 in Germany Germany Up
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

  Files folder image Files (54)  /  Psr  
File Role Description
Files folder imageLog (8 files)

  Files folder image Files (54)  /  Psr  /  Log  
File Role Description
  Plain text file AbstractLogger.php Class Class source
  Plain text file InvalidArgumentException.php Class Class source
  Plain text file LoggerAwareInterface.php Class Class source
  Plain text file LoggerAwareTrait.php Class Class source
  Plain text file LoggerInterface.php Class Class source
  Plain text file LoggerTrait.php Class Class source
  Plain text file LogLevel.php Class Class source
  Plain text file NullLogger.php Class Class source

  Files folder image Files (54)  /  SKien  
File Role Description
Files folder imagePNServer (9 files, 1 directory)
Files folder imageTest (1 directory)

  Files folder image Files (54)  /  SKien  /  PNServer  
File Role Description
Files folder imageUtils (4 files)
  Plain text file PNDataProvider.php Class Class source
  Plain text file PNDataProviderMySQL.php Class Class source
  Plain text file PNDataProviderSQLite.php Class Class source
  Plain text file PNEncryption.php Class Class source
  Plain text file PNPayload.php Class Class source
  Plain text file PNServer.php Class Class source
  Plain text file PNServerHelper.php Class Class source
  Plain text file PNSubscription.php Class Class source
  Plain text file PNVapid.php Class Class source

  Files folder image Files (54)  /  SKien  /  PNServer  /  Utils  
File Role Description
  Plain text file Curve.php Class Class source
  Plain text file Math.php Class Class source
  Plain text file NistCurve.php Class Class source
  Plain text file Point.php Class Class source

  Files folder image Files (54)  /  SKien  /  Test  
File Role Description
Files folder imagePNServer (12 files, 1 directory)

  Files folder image Files (54)  /  SKien  /  Test  /  PNServer  
File Role Description
Files folder imagetestdata (6 files)
  Plain text file PNDataProviderMySQLTest.php Class Class source
  Plain text file PNDataProviderSQLiteTest.php Class Class source
  Plain text file PNDataProviderTest.php Class Class source
  Plain text file PNEncryptionTest.php Class Class source
  Plain text file PNPayloadTest.php Class Class source
  Plain text file PNServerTest.php Class Class source
  Plain text file PNSubscriptionTest.php Class Class source
  Plain text file PNVapidTest.php Class Class source
  Plain text file TestHelperTrait.php Class Class source
  Plain text file UtilsCurveTest.php Class Class source
  Plain text file UtilsMathTest.php Class Class source
  Plain text file UtilsPointTest.php Class Class source

  Files folder image Files (54)  /  SKien  /  Test  /  PNServer  /  testdata  
File Role Description
  Accessible without login Plain text file expired_subscription.json Data Auxiliary data
  Accessible without login Plain text file gone_subscription.json Data Auxiliary data
  Accessible without login Plain text file invalid_subscription.json Data Auxiliary data
  Accessible without login Plain text file inv_endpoint_subscription.json Data Auxiliary data
  Accessible without login Plain text file notfound_subscription.json Data Auxiliary data
  Accessible without login Plain text file valid_subscription.json Data Auxiliary data

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,100
This week:1
All time:1,863
This week:34Up
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:24