Solved

Use of punctuation in twilio sms api

Posted on 2011-03-22
7
936 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 1

Assisted Solution

by:Imaginx
Imaginx earned 0 total points
Comment Utility
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 108

Accepted Solution

by:
Ray Paseur earned 500 total points
Comment Utility
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
Comment Utility
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 108

Expert Comment

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

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

Why do we like using grid based layouts in website design? Let's look at the live examples of websites and compare them to grid based WordPress themes.
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

772 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now