Viewed   145 times

I noticed Facebook started using the HTML5 notification for desktop and I thought I would start dabbling in it for fun for my blog. My idea is pretty simple: new blog comes out, apache cronjob runs every X minutes and calls a file, does some PHP wizardry and out goes the notification.

I have looked online and found examples using node.js and angular, but I'm not comfortable using either of those so I'd rather stick with PHP.

Here is my process: The user goes to my blog and will click a button to allow notifications. For brevity, the below code sends the users a notification when they click the "notify" button. This works perfectly, and in theory should subscribe them to any future notifications.

if ('Notification' in window) {

function notifyUser() {
    var title = 'example title';
    var options = {
        body: 'example body',
        icon: 'example icon'

    if (Notification.permission === "granted") {
        var notification = new Notification(title, options);
    } else if (Notification.permission !== 'denied') {
        Notification.requestPermission(function (permission) {
            if (permission === "granted") {
                var notification = new Notification(title, options);


$('#notify').click(function() {
    return false;

} else {
    //not happening

You can see the fiddle of the above.

Access to the user is granted and now I should be able to send them notifications whenever I want. Awesome! I then write up a blog entry and it has the ID of XYZ. My cronjob goes and calls the following PHP script, using the above node.js example as a template.

(In this example I am just calling the script manually from my phone and watching my desktop screen. Since my desktop is "subscribed" to the same domain, I think the following would/should work.)

$num = $_GET['num'];

$db = mysql_connect(DB_HOST, DB_USER, DB_PASS);
if($db) {
    mysql_select_db('mydb', $db);
    $select = "SELECT alert FROM blog WHERE id = ".$num." && alert = 0 LIMIT 1";
    $results = mysql_query($select) or die(mysql_error());
    $output = '';
    while($row = mysql_fetch_object($results)) { 

        $output .= "<script>

        var title = 'new blog!';
        var options = {
            body: 'come read my new blog!',
            icon: 'same icon as before or maybe a new one!'

        var notification = new Notification(title, options);


      $update = "UPDATE blog SET alert = 1 WHERE id = ".$num." && alert = 0 LIMIT 1";
      mysql_query($update) or die(mysql_error());


    echo $output;


I then check the database and blog entry XYZ's "alert" is now set to "1", yet my desktop browser never got notified. Since my browser is subscribed to the same URL that is pushing out the notification, I would imagine I'd get a message.

Either I'm doing something wrong (perhaps PHP isn't the right language for this?), or I'm misunderstanding the spec. Could somebody help point me in the right direction? I think I'm missing something.

Thanks a lot.

Update 1

According to the comments, if I just call a script with this in it:

 var title = 'new blog!';
 var options = {
    body: 'come read my new blog!',
    icon: 'same icon as before or maybe a new one!'

  var notification = new Notification(title, options);

It should hit all devices that are subscribed to my notifications. I tried this on my phone but my desktop still didn't get a notification. I still think I'm missing something as my notifications seem stuck to one device and can only be called on page-load or on click as opposed to Facebook which sends you notifications even if the page isn't open in your browser.



Your problem is the lack of AJAX to connect Javascript and PHP. The way your PHP script works is by manually running the script, so only the device hitting that script will see the notification. There is nothing that actually sends that info to your other device right now.

To better explain the problem, your desktop may have allowed access to the notifications, but it doesn't automatically pull in those notifications. The code you have provided will need to use AJAX to hit the script URL, instead of using it as a cron job.

First off, you need to start a repeating request to the PHP script to see if there has been any updated notification. If there is a new notification, then you need to create a new notification object using the returned response.

Second, you need to alter the PHP script to output a JSON string rather instead of the notification script.

JSON output example:

    title: 'new blog!',
    options: {
      body: 'come read my new blog!',
      icon: 'same icon as before or maybe a new one!'
    title: 'another blog item!',
    options: {
      body: 'come read my second blog!',
      icon: 'hooray for icons!'

Your notifyUsers() should take title and option as arguments instead of hardcoding them:

function notifyUser(title, options) { ... }

Using jQuery, get the PHP response and create the notification:

function checkNotifications(){
  $.get( "/path/to/script.php", function( data ) {
    // data is the returned response, let's parse the JSON string
    json = JSON.parse(data);

    // check if any items were returned
      // send each item to the notify function
      for(var i in json){
        notifyUser(json[i].title, json[i].options);

  setTimeout(checkNotifications, 60000); // call once per minute

Now, you just need to kickstart the AJAX polling, so add this to your webpage:


That's pretty much it! You were just missing the part when your desktop needed to pull in the notifications. Heads up though, this isn't tested and you may need to tweek something.

Sunday, October 23, 2022

I got a solution for this.


$read = array($this->_apnsConnection);
$null = null;
$changedStreams = stream_select($read, $null, $null, 0, 1000000);

if ($changedStreams === false) {    

    $this->_log("Error: Unabled to wait for a stream availability");
} elseif ($changedStreams > 0) {

    $responseBinary = fread($this->_apnsConnection, 6);
    if ($responseBinary !== false || strlen($responseBinary) == 6) {

        $response = unpack('Ccommand/Cstatus_code/Nidentifier', $responseBinary);
Saturday, November 12, 2022

With FCM you specify a POST payload to send to In that payload you can specify a data or a notification key, or both.

If your payload contains only a data key, your app will handle all push messages itself. E.g. they are all delivered to your onMessageReceived handler.

If your payload contains a notification key, your app will handle push messages itself only if your app is active/in the foreground. If it is not (so it's in the background, or closed entirely), FCM handles showing the notification for you by using the values you put into the notification key payload.

Note that notifications sent from a console (like Firebase console), they always include a notification key.

Looks like you want to be handling the FCM messages yourself so you can customize the notification a bit more etc, so it would be better to not include the notification key in the POST payload, so all push messages are delivered to your onMessageReceived.

You can read more about it here:
Advanced messaging options
Downstream message syntax

Wednesday, September 28, 2022

You are sending push notification one by one . That's why it takes too much time. You can send group message using device id. Check this documentation .

Use below code for sending push notification to android. Same way you can do this on iOS also.

//For andriod
    $get_result = mysql_query("SELECT ps_mobile_id FROM push_service where ps_service_type = 1", $con);

   // $row_result = mysql_fetch_assoc($get_result);
    $totalRows_row_result = mysql_num_rows($get_result);


         while($row = mysql_fetch_assoc($get_result)){
            $MobIDs[] = $row;
     $params = array("pushtype"=>"android", "msg"=>$msg, "subject_main"=>$subject_main, "subject_notify"=>$subject_notify, );
    $rtn = $push->sendMessageAndroid($MobIDs, $params)

and sendMessageAndroid($registration_id, $params)

 public $androidAuthKey = "Android Auth Key Here"; 
public $iosApnsCert = "./certification/xxxxx.pem"; 

 * For Android GCM 
 * $params["msg"] : Expected Message For GCM 
private function sendMessageAndroid($registration_id, $params) { 
    $this->androidAuthKey = "Android Auth Key Here";//Auth Key Herer 

    ## data is different from what your app is programmed 
    $data = array( 
            'registration_ids' => array($registration_id), 
            'data' => array( 
                            'gcm_msg' => $params["msg"] 

    $headers = array( 

    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_URL, ""); 
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); 
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); 
    curl_setopt($ch, CURLOPT_POST, true); 
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); 
    $result = curl_exec($ch); 
    //result sample {"multicast_id":6375780939476727795,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1390531659626943%6cd617fcf9fd7ecd"}]} 
    // // refer error code 

    $rtn["code"] = "000";//means result OK 
    $rtn["msg"] = "OK"; 
    $rtn["result"] = $result; 
    return $rtn; 


Please note that: Don't send more than 1000 device id per request. If you have more than 1000 users. then slice your MobIDs with a size less than 1000

Tuesday, December 6, 2022

try this code.Its working fine for me.just change key and token

define('API_ACCESS_KEY','Api key from Fcm add here');
 $fcmUrl = '';

     $notification = [
            'title' =>'title',
            'body' => 'body of message.',
            'icon' =>'myIcon', 
            'sound' => 'mySound'
        $extraNotificationData = ["message" => $notification,"moredata" =>'dd'];

        $fcmNotification = [
            //'registration_ids' => $tokenList, //multple token array
            'to'        => $token, //single token
            'notification' => $notification,
            'data' => $extraNotificationData

        $headers = [
            'Authorization: key=' . API_ACCESS_KEY,
            'Content-Type: application/json'

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$fcmUrl);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fcmNotification));
        $result = curl_exec($ch);

        echo $result;
Monday, October 10, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :