1

I have a PHP script that is called via a Twilio webhook for incoming SMS. Messages come in with post data that I capture with:

$Message = $_POST["Body"];

Then, using the Twilio PHP SDK, that message is forwarded back out to a mobile phone via:

$relay = new Client($sid, $token);
try {
    $relay->messages->create(
        '+15558675310',
        array(
            'from' => '+15555555555',
            'body' => $Message
        )
    );
}
catch (Exception $e) {
    $TwilioError = "Error: " . $e->getMessage();
}

Simple enough and works fine. The problem is emojis aren't translated properly and are sent out garbled. What should be a smiley face goes out as: 😀

The Twilio logs will show the incoming message with the smiley face, but that's just an HTML representation. The log doesn't show what the encoding is (assuming UTF-8). The Twilio log for the outgoing message says the encoding is UCS2.

The web server default encoding is UTF-8.

What needs to be done, using PHP 5.6, with the message coming in from Twilio with possible emojis in the content before sending back out via the Twilio PHP SDK?

Data Do IT
  • 11
  • 4
  • Twilio developer evangelist here. For information, all the dealings between your application and Twilio should be done in UTF-8. UCS2 is the encoding that Twilio uses to send the message to the phone network, but Twilio translates that to UTF-8 and back again to make it easy to work with. When you say that the web server default encoding is UTF-8 where is that set? Are you able, from your PHP application, to print an emoji character to a log or page of output? – philnash Dec 19 '18 at 23:04
  • php.ini: default_charset = "UTF-8" Also: header("Content-Type: text/html; charset="utf-8"); – Data Do IT Dec 20 '18 at 19:02

1 Answers1

0

Solved. Part of my problem was calling stripslashes() on the $_REQUEST['Body'], likely out of habit to aid in other nefarious post values. Thus, it was stripping out the UTF-8 emoji bytes.

Once that was removed I was able to send on the emoji. For storing the emoji for logging purposes, utilizing the entities function provided by @PetrHejda below works flawlessly.

htmlentites not working for emoji

Data Do IT
  • 11
  • 4