I have a PHP script for sending push notification message to phones. We are able to send and receive the normal messages perfectly. But when I use aphostrophe(') in the message, we are not able to receive messages in the phones. After googling it out I have found one function in PHP [addslashes($variable_name)]. Now when i use this function, we are receiving the messages but not like it is intended so, meaning I am getting "\" where ever there is aphostrophe (') in a notification message.
For example, 1) Hello Everyone !!! - When I send this message, we are able to get the push notification message.
2) come on Let's Play the game !!! - When I send this message, first of all, we are not able to get the message, but when I use the php function [addslashes()] then we get the message but not correctly, We get the message like this - come on Let\'s Play the game (notice that there is a backslash() before aphostrope(') (Let\'s)), which is not the correct message.
Any help is much appreciated, Thanks in advance!!!
My PHP Code:
$msg = $_POST['messageTxt']; // Gets the Notification Message from the User
$message = addslashes($msg);
$device_token ="************************************************************";
$device = $device_token;
$payload['aps'] = array('alert' => $message, 'badge' => +1, 'sound' => 'default');
$payload = json_encode($payload);
$options = array('ssl' => array(
'local_cert' =>'****',
'passphrase' => '*****'
));
/////////////////////////////////////////////////////////////////////////////////
// APNS SERVER CONNECTIVITY //
/////////////////////////////////////////////////////////////////////////////////
$streamContext = stream_context_create();
stream_context_set_option($streamContext, $options);
$apns = stream_socket_client('ssl://gateway.push.apple.com:2195', $error, $errorString, 60, STREAM_CLIENT_CONNECT, $streamContext);
$apnsMessage = chr(0) . chr(0) . chr(32) . pack('H*', str_replace(' ', '', $device)) . chr(0) . chr(strlen($payload)) . $payload;
// echo $apnsMessage.'<br> <br>';
$res=fwrite($apns, $apnsMessage);
$payload ='';
$apnsMessage='';
fclose($apns); // Closes the APNS Sercer Connection
Though I have no specific experience with push messages, I would try to solve json coding-decoding problems with json "native" encoding options, no php addslashes()
or whatsoever.
Try json_encode()
options, particularly:
json_encode($payload, JSON_HEX_QUOT);
I would also test for other possible issues with other special chars (<, >, &, etc...) and test corresponding json_encode()
options.
http://php.net/manual/en/function.json-encode.php (see param int $options = 0
)
http://php.net/manual/en/json.constants.php (see JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, and maybe JSON_UNESCAPED_SLASHES combined with addslashes()
)