Push Notification In PHP

Push Notifications are very common and most used these days in all apps. Here I am posting a complete function to send Push Notifications in Android and IOS devices using PHP. You cn easily use this in your mobile app APIs.

Requirements:

For Android:
@ GCM key of APP
How to generate: For generating GCM key(Google Cloud Messaging). You can create a project at https://console.developers.google.com/project
You can find a lot of tutorials in google to create GCM key for push notification.

For IOS:
@ PEM file
How to generate: PEM file can only be generated by mac system. There are lots of articles for creating this file (but ofcourse you need a mac)

Here is a complete function in PHP to send notifications in Android/ios APPS.

Function Requirements

1)message:message to be sent in notification
2)deviceToken: token generated for device by gcm or pem
3)devicetype:android/ios
4)batchcount: just a number (you can manage in db)

<?php
function sendRegistryNotification($message, $deviceToken, $deviceType, $batchcount)
        {              
            $message="New blog published : ".$message;
            $batchcount=$batchcount; //the  count which is shown in notifications (like 2 messages recieved)         
            $path='/var/www/html/notification/APNS.pem';  //path of pem file  for your app       
            $deviceType = strtolower($deviceType);
            switch ($deviceType) {
                case 'ios':
                   $pemPath = $path; // replace with the path to PEM file
                   $ctx = stream_context_create();
                   stream_context_set_option($ctx, 'ssl', 'local_cert', $pemPath);

                   $fp = stream_socket_client('ssl://gateway.push.apple.com:2195',
                       $err,
                       $errstr,
                       60,
                       STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT,
                       $ctx);
                       // Create the payload body
                       $body['aps'] = array(
                           'badge' => +$batchcount,
                           'alert' => $message,
                           'sound' => 'default'
                       );
                       $payload = json_encode($body);
                       // Build the binary notification
                       $msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;
                       // Send it to the server
                       $result = fwrite($fp, $msg, strlen($msg));
                      // var_dump($result);
                       if (!$result)
                       {
                           fclose($fp);
                           return false;
                       }                                       
                       else
                       {
                           fclose($fp);
                           return true;                  
                       }                
                    break;
                case 'android':
                   $message = array("message" => $message,'title'=> 'phpblog','msgcnt'=>$batchcount);
                   // Set POST variables
                   $url = 'https://android.googleapis.com/gcm/send';

                   $fields = array(
                       'registration_ids' => array($deviceToken),
                       'data' => $message,
                   );

                   $headers = array(
                       'Authorization: key='.'MSKDJFKLSAJFLDS-SDFSAFDS4dXZblt0JBPi4TBaneQ',
                       'Content-Type: application/json'
                   );  // Key For your App(find in your project which was created in <a href="https://console.developers.google.com/project" target="_blank">https://console.developers.google.com/project</a>
                   // Open connection
                   $ch = curl_init();
                   // Set the url, number of POST vars, POST data
                   curl_setopt($ch, CURLOPT_URL, $url);
                   curl_setopt($ch, CURLOPT_POST, true);
                   curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
                   curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                   // Disabling SSL Certificate support temporarly
                   curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                   curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
                   // Execute post
                   $result = curl_exec($ch);
                   //var_dump($result);
                   if ($result === FALSE) {
                    //   die('Curl failed: ' . curl_error($ch));
                   }
                   // Close connection
                   curl_close($ch);
                   return TRUE;
                    break;
            }
            return true;
        }
?>

That’s all. You are done 🙂