In a system where both students and doctors communicate via a website and mobile application, it becomes essential to implement push notifications for instant updates. This article provides a comprehensive solution for sending push notifications to multiple iPhone users from a PHP website.
To enable push notifications, each user's device token is stored during registration. Next, a simple PHP function like the one provided can be employed to send messages.
function sendPushNotification($deviceToken, $message) {
// Initialize variables
$ctx = stream_context_create();
$passphrase = 'my_passphrase';
$certificatePath = 'ckipad.pem';
// Establish SSL connection
stream_context_set_option($ctx, 'ssl', 'local_cert', $certificatePath);
stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
$fp = stream_socket_client('ssl://gateway.sandbox.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $ctx);
if (!$fp) {
exit("Failed to connect: $err $errstr" . PHP_EOL);
}
// Create payload
$payload = array(
'aps' => array(
'badge' => 1,
'alert' => $message,
'sound' => 'default'
)
);
// Encode payload
$payload = json_encode($payload);
// Build binary notification
$msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;
// Send notification
$result = fwrite($fp, $msg, strlen($msg));
if (!$result) {
echo 'Message not delivered' . PHP_EOL;
} else {
echo 'Message successfully delivered:' . $message . PHP_EOL;
}
// Close connection
fclose($fp);
}
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3