Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Use of punctuation in twilio sms api

Posted on 2011-03-22
7
Medium Priority
?
1,052 Views
Last Modified: 2012-05-11
I have a php script that sends a string that could contain slashes, quotes, anything through Twilio's API ...

Today, I sent one single quote through & now I can't get the service to recognize the body of my messages anymore ...

I've emailed them - but I've PATIENTLY waiting a replay for hours now ... I'm stuck !!
0
Comment
Question by:Imaginx
  • 3
  • 2
  • 2
7 Comments
 
LVL 7

Expert Comment

by:Swafnil
ID: 35197856
If you are dealing with a black box like an API not being documented, it's always a good idea to escape data as much as needed i.e. through removing special characters or replacing them with something else.

In case you are calling a service via REST, remember to urlencode() [1] data before sending it, i.e.
$msg= urlencode(strip_tags('This is my messed-up text with \' " /\ and the like'));

Open in new window


Could you post a snippet how you are calling the Twilio API inside of your PHP file?
0
 
LVL 1

Author Comment

by:Imaginx
ID: 35197982
I'll post code today when I'm at work. I'm using urlencode now & I added stripslashes as well to get it to work. It is a REST service.

After the problem I experienced yesterday, I'm nervous of others that could arise ...
0
 
LVL 7

Expert Comment

by:Swafnil
ID: 35198193
I don't know if this applies to all SMS notifications sent through Twilio, but it seems as if a maximum of 160 characters is allowed; depending on the way Twilio handles incoming REST calls, urlencoded characters can easily break that limit. There are some useful topics in the debug section of their homepage, i.e.:
* Twilio Debugging Interface [1]
* Notification REST API, query for logs [2]

All information found here:

Debugging your application [3]

Good luck and keep us posted!

[1] http://www.twilio.com/user/account/debugger
[2] http://www.twilio.com/docs/api/rest/notification
[3] http://www.twilio.com/docs/errors/
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 1

Assisted Solution

by:Imaginx
Imaginx earned 0 total points
ID: 35198515
lol ... I read all those articles yesterday as my hair was turning grey trying to figure out my problem ..

Here's their class:
 
public function request($path, $method = "GET", $vars = array()) {
            $fp = null;
            $tmpfile = "";
            $encoded = "";
            foreach($vars AS $key=>$value)
                $encoded .= "$key=".urlencode($value)."&";
            $encoded = substr($encoded, 0, -1);
            
            // construct full url
            $url = "{$this->Endpoint}/$path";
            
            // if GET and vars, append them
            if($method == "GET") 
                $url .= (FALSE === strpos($path, '?')?"?":"&").$encoded;

            // initialize a new curl object            
            $curl = curl_init($url);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
            switch(strtoupper($method)) {
                case "GET":
                    curl_setopt($curl, CURLOPT_HTTPGET, TRUE);
                    break;
                case "POST":
                    curl_setopt($curl, CURLOPT_POST, TRUE);
                    curl_setopt($curl, CURLOPT_POSTFIELDS, $encoded);
                    break;
                case "PUT":
                    // curl_setopt($curl, CURLOPT_PUT, TRUE);
                    curl_setopt($curl, CURLOPT_POSTFIELDS, $encoded);
                    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
                    file_put_contents($tmpfile = tempnam("/tmp", "put_"),
                        $encoded);
                    curl_setopt($curl, CURLOPT_INFILE, $fp = fopen($tmpfile,
                        'r'));
                    curl_setopt($curl, CURLOPT_INFILESIZE, 
                        filesize($tmpfile));
                    break;
                case "DELETE":
                    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE");
                    break;
                default:
                    throw(new TwilioException("Unknown method $method"));
                    break;
            }
            
            // send credentials
            curl_setopt($curl, CURLOPT_USERPWD,
                $pwd = "{$this->AccountSid}:{$this->AuthToken}");
            
            // do the request. If FALSE, then an exception occurred    
            if(FALSE === ($result = curl_exec($curl)))
                throw(new TwilioException(
                    "Curl failed with error " . curl_error($curl)));
            
            // get result code
            $responseCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
            
            // unlink tmpfiles
            if($fp)
                fclose($fp);
            if(strlen($tmpfile))
                unlink($tmpfile);
                
            return new TwilioRestResponse($url, $result, $responseCode);
        }
    }

Open in new window


Here's my new code (calling the method):
 
$cleanBody=stripslashes($body);
$messageArray=array("To" => $recipient,"From" => $longcode,"Body" => "$senderAlias: $cleanBody");
$response = $client->request("/$ApiVersion/Accounts/$AccountSid/SMS/Messages","POST",$messageArray);

Open in new window


Here's my old code (calling the method):
 
$response = $client->request("/$ApiVersion/Accounts/$AccountSid/SMS/Messages", 
"POST", array("To" => $recipient,"From" => "415-599-2671","Body" => "$senderAlias: $body";));

Open in new window


You can see where I added the stripslashes() - Everything seemed to work after that, but I'm not totally comfortable with the data going through urlencode .. People type random things into txt messages - I don't want it to break again ..

0
 
LVL 111

Accepted Solution

by:
Ray Paseur earned 2000 total points
ID: 35199158
Is there a genuine need to send special characters?  If not, you might want to sanitize the strings with something like this to remove all the unwanted stuff.

$safe_string = preg_replace('#[^A-Z 0-9]#i', ' ', $user_string); // DISCARD ALL NON-ALPHANUMERIC CHARACTERS

If there is a need to send the special characters, then urlencode() is probably the best way to go.

About stripslashes - it may be that your PHP installation has magic-quotes set to "on."  I would want it to be off for my work.
http://us2.php.net/manual/en/security.magicquotes.php

Best regards, ~Ray
0
 
LVL 1

Author Closing Comment

by:Imaginx
ID: 35239099
Yet again ... Thanks for the direction Ray.

stripslashes works, but it isn't necc if magic_quotes wasn't on.

during the development stage, this is hosted on a shared server.

once it's live (Possibly as early as May 1st.. whew) - we'll take it to a vps where I'll have control over security settings like this one...
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 35240049
Thanks for the points - it's a great question, ~Ray
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

There are times when I have encountered the need to decompress a response from a PHP request. This is how it's done, but you must have control of the request and you can set the Accept-Encoding header.
The first step to building an amazing About page is to figure out what you want the page to say about your company. You then must grab the attention of the reader, boast a bit, tell a story and let others brag about you. With a little bit of thought…
Viewers will get an overview of the benefits and risks of using Bitcoin to accept payments. What Bitcoin is: Legality: Risks: Benefits: Which businesses are best suited?: Other things you should know: How to get started:
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
Suggested Courses

782 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question