1

I'm building a WordPress plugin in PHP to let customers send push notifications to mobile apps using OneSignal. I have a function that is both form and datahandler in that the action is recursive:

<form name='fcnaddpush' id='fcnaddpush' action="<?php echo $_SERVER['REQUEST_URI']; ?>" METHOD="POST" />

When the user clicks the submit button, the function calls itself and then parses out values entered in the form, creates an array, preps with json_encode(), then submits via cURL to OneSignal's REST API. It all works quite nicely, until.......

If the title or content contains an apostrophe it creates a problem. $_POST['title'] comes back with \' in the string, and json_encode double escapes it, so now it's has become it\'s. When the push notification arives with the double escaped apostrophe, the javascript function that displays the notification dies, and because the string has been written to a file on the mobile device, no notifications can be shown old or new without uninstalling and reinstalling the app.

SEEMINGLY I can solve this problem by using stripslashes($_POST['title']) before calling json_encode().

The question is, I suppose, are there going to be unintended consequences with other "special characters" when using stripslashes()? Is there a way to tell the POST method to use utf-8 instead of urlencode? Would that even work?

Ed Tiley
  • 13
  • 6
  • 3
    http://php.net/manual/en/function.json-encode.php -> options -> `JSON_HEX_QUOT` and `JSON_HEX_APOS` – bassxzero Mar 23 '17 at 12:49
  • 1
    Are you doing json_encode($_POST) directly? can you show us an example of the input and the contents of the encoded string? – ffflabs Mar 23 '17 at 12:49
  • @bassxzero much knowledge, such options. I learnt something new. – ffflabs Mar 23 '17 at 12:50
  • Ed did the encode options work for you? – bassxzero Mar 23 '17 at 13:00
  • @bassxzero Unfortunately, no. While it does send the apostrophe back as \u0027 json_encode() fails to remove the original \ character, so the encoded apostrophe shows up as: It\\\u0027s a girl! TRIPLE escaped! Judging by the list of constants, however, if the quote and apos are the only two characters to worry about, then stripslashes() will do the trick it seems. – Ed Tiley Mar 23 '17 at 18:16
  • @bassxzero The solution lies within how your app responds to the notification coming in to the mobile app AFTER OneSignal breaks it down. It is actually not necessary to use any of the JSON constants/options in sending a notification, which is where the unfortunately no, part comes in. Thanks for your help. It pointed me in the right direction. – Ed Tiley Mar 24 '17 at 18:25

0 Answers0