While developing web services you may need PHP code to send push notifications on IOS devices. Here is the PHP code to send IOS push notifications.
To send the push notifications we need 2 things from Apple:
- pem file
- Passphrase
Remember pem file is different for development and production.
Now if you have device token of ios device token also please try the below code, It will send the push notification to the IOS device.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
|
<?php
class Notification
{
public function sendtNotification($deviceToken,$lat,$long) {
$data = array('latitude' => $lat,
'longitude' => $long
);
// Put your private key's passphrase here:
$passphrase = '';
////////////////////////////////////////////////////////////////////////////////
$ctx = stream_context_create();
$env = 'dev';
if($env == 'produnction')
{
stream_context_set_option($ctx, 'ssl', 'local_cert', 'production.pem');
$fp = stream_socket_client(
'ssl://gateway.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $ctx);
}
else
{
stream_context_set_option($ctx, 'ssl', 'local_cert', 'dev.pem');
$fp = stream_socket_client(
'ssl://gateway.sandbox.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $ctx);
}
//
stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
if (!$fp)
exit("Failed to connect: $err $errstr" . PHP_EOL);
//echo 'Connected to APNS' . PHP_EOL;
// Create the payload body
/// set content-available 1 for silent notifications else you can remove it
$body['aps'] = array(
'data' => $data,
'content-available' => '1'
);
// Encode the payload as JSON
$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
fwrite($fp, $msg, strlen($msg));
// $result = fwrite($fp, $msg, strlen($msg));
/* if (!$result)
echo 'Message not delivered' . PHP_EOL;
else
echo 'Message successfully delivered' . PHP_EOL; */
// Close the connection to the server
fclose($fp);
}
}
$notification_obj = new Notification();
$notification_obj->sendtNotification('deviceToken','23.3242342','43.2432432');
?>
|