Question

thanks in advance to those who will help

when I send a push notification to a single device i use this methodology

<?php


  $deviceToken = $_POST['TOKEN'];
  $message = $_POST['MESSAGGIO'];

  $badge = 0;
  $sound = "default";

  $body = array();
  $body['aps'] = array("alert" => $message);


  if ($badge)
        $body['aps']['badge'] = $badge;
  if ($sound)
        $body['aps']['sound'] = $sound;

  $ctx = stream_context_create();
  stream_context_set_option($ctx, "ssl", "local_cert", "apns-dev.pem");

  $fp = stream_socket_client("ssl://gateway.push.apple.com:2195", $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx);

  if (!$fp) {
       echo json_encode("errore");
       return;
  } 

  $payload = json_encode($body);

  $msg = chr(0) . pack("n",32) . pack("H*", str_replace(" ", "", $deviceToken)) . pack("n",strlen($payload)) . $payload;

  fwrite($fp, $msg);

  fclose($fp);


?>

while when I have to send a notification to all the devices in my database (using the device token of course), I would have thought of doing so

<?php

  $deviceToken = $_POST['TOKEN'];
  $message = $_POST['MESSAGGIO'];

  $badge = 0;
  $sound = "default";

  $body = array();
  $body['aps'] = array("alert" => $message);


  if ($badge)
        $body['aps']['badge'] = $badge;
  if ($sound)
        $body['aps']['sound'] = $sound;

  $ctx = stream_context_create();
  stream_context_set_option($ctx, "ssl", "local_cert", "apns-dev.pem");

  $fp = stream_socket_client("ssl://gateway.push.apple.com:2195", $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx);

  if (!$fp) {
   echo json_encode("errore");
   return;
  } 

  $payload = json_encode($body);

  //****

  $db = new PDO('sqlite:my_db.sqlite');

  $query = "SELECT device_token FROM user";
  $result = $db->query($query);

  foreach($result as $row){
    $msg = chr(0) . pack("n",32) . pack("H*", str_replace(" ", "", $row['device_token'])) . pack("n",strlen($payload)) . $payload;
    fwrite($fp, $msg);
  }

  //****

  fclose($fp);

?>

is a correct solution according to you?

Was it helpful?

Solution

It looks correct. You are using the same connection to send all the messages, which is the most important thing when sending multiple notifications.

However, you are using the simple binary format, which has no support for error responses, and therefore you have no error handling. This will work assuming your message never exceeds the max payload length and all the device tokens in your DB are valid. A better approach would be to use the enhanced binary format and read (and handle) error responses.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top