WeberDev.com PHP and MySQL Code

LOG IN
BEGINNER GUIDES  |  PHP CLASSES  |  CODE SEARCH  |  ARTICLES SEARCH  |  PHP FORUMS  |  PHP MANUAL  |  PHP FUNCTIONS LIST  |  WEB SITE TEMPLATES
Start typing to search for PHP and MySQL Code Snippets and Articles Search
Submit a code Example / Snippet Submit Your Code
Search Engine Optimization Monitor SEO Monitor
Web Site UpTime Monitor UpTime Monitor
WeberDev's Monthly code contest PHP Code Contest
Your Personal Examples List My Favorite Examples
Your Personal Articles List My Favorite Articles
Edit Account Info Update Your Profile
PHP Code Search
Web Development Forums
Learn MySQL Playing Trivia
PHPBB2 Templates
Web Development Index
Web Development Resources
Web Development Content
PHPClasses
PHP Editor
PHP Jobs
Vision.To Design
Ajax Tutorials
PHP Programming Help
PHP/MySQL Programming
Webmaster Resources
Webmaster Forum
XML meta language
website builder
Mobile Dev World

Go Back Add a Comment Send this Article to a friend Add this Article to your personal favoritest for easy future access to your favorite Code Examples and Articles. Submit a code example Print this code example.
BACK ADD A COMMENT SEND TO A FRIEND ADD TO MY FAVORITES SUBMIT AN ARTICLE PRINT
Title : Send SMS Thru HTTP
Categories : PHP, SMS, HTTP Picture not available
Farheen Rehman
Date : 2005-05-17
Grade : 5 of 5 (graded 1 times)
Viewed : 10091
Search : More Articles by Farheen Rehman
Action : Grade This Article
Tools : My Favotite Articles


  Submit your own code examples 
 


Introduction

SMS (also known as text-messaging) has grown into a very popular method of communication. It has been around in Europe and Asia since the early nineties and its use is steadily increasing in the US as well.

SMS stands for "Short Message Service" and uses mobile phones to transmit (surprise, surprise) short messages to and from mobile phones and whilst many of us might not know this, it is also possible to send SMS messages from a website or a piece of software.

There are an infinite number of reasons why you might want to use your website to send SMS. You might want to add a "send by SMS" option to your headlines, for example, or you might want to provide 24/7 support in which your technician is alerted by SMS or you might simply want to provide your viewers with Free SMS to drive traffic to your site.

Although it is also possible to send SMS via e-mail, this tutorial will teach you how to send SMS using GET and POST HTTP methods in PHP (since it's the language I know).

For those of us that many not know this, using HTTP basically means the use of forms, just like a contact form, except that these will be submitted automatically as opposed to manually.

Although this tutorial can be used for any gateway that provides access via HTTP, it is based on TM4B's SMS Gateway because :

  • they are the only gateway I know that have a simulation mode for tweaking your scripts,
  • they don't have any set-up fees,
  • their prices are low,
  • they are reliable and
  • I use them.


Understand the Requirements of the Gateway

Full details about connecting to TM4B are provided on their SMS API page. They basically require us to provide six mandatory pieces of data:


  • username: our username
  • password: our password
  • msg: our SMS message(s)
  • to: the recipient(s) of our message
  • from: our sender id
  • route: the route of the message (i.e. first class or business class)


And we will add a seventh, which is "sim". This identifies that our message is only a simulation and so credits won't be removed from our account and messages won't actually be delivered.
Prepare the Request

Now the actual message-delivery process is handled by the gateway. All they want us to do is pass them the details of the message(s) in the form of an HTTP request, similar to this one:


http://www.tm4b.com/client/api/send.php?
username=abcdef&password=12345&msg=This+is+sample+message.&
to=447768254545%7C447956219273%7C447771514662
&from=MyCompany&route=frst&sim=yes


You can test the above example (which uses GET) by pasting it into your browser's address bar. You should get a response saying that the username is invalid, which is normal because this is just to demonstrate.

The first step is to save our data as variables and then convert them into a URL request. There are different ways of doing this, but this is a very innovative and useful way:


<?php
$request
= ""; //initialize the request variable
$param["username"] = "abcdef"; //this is the username of our TM4B account
$param["password"] = "12345"; //this is the password of our TM4B account
$param["msg"] = "This is sample message."; //this is the message that we want to send
$param["to"] = "447768254545|447956219273|447771514662"; //these are the recipients of the message
$param["from"] = "MyCompany";//this is our sender
$param["route"] = "frst";//we want to send the message via first class
$param["sim"] = "yes";//we are only simulating a broadcast

foreach($param as $key=>$val) //traverse through each member of the param array
{
$request.= $key."=".urlencode($val); //we have to urlencode the values
$request.= "&"; //append the ampersand (&) sign after each paramter/value pair
}
$request = substr($request, 0, strlen($request)-1); //remove the final ampersand sign from the request
?>




We assign our credentials and routing information in the $param array. You'll notice that multiple recipients can be defined by separating them with the pipe-character. Each parameter value needs to be urlencoded and multiple key/value pairs are separated by ampersands. A final ampersand probably would not cause any problems but substr is still used to produce a tidy request.

The script will produce the following request that can be sent to the SMS gateway:


username=abcdef&password=12345&msg=This+is+sample+message.&
to=447768254545%7C447956219273%7C447771514662&
from=MyCompany&route=frst&sim=yes


Sending the request with CURL

Previously we saw that the request could be executed by pasting it into the browser window. But what we really want is for this to take place behind the scenes. The following code does exactly that using CURL.

CURL is a very impressive library that allows you to connect and communicate to many different types of servers with many different types of protocols. You can find more info in the PHP Manual.

This code opens up a connection with the gateway, sends the SMS message(s) and collects their message IDs which are presented within the response header.


<?php
$url
= "http://www.tm4b.com/client/api/send.php"; //this is the url of the gateway's interface
$ch = curl_init; //initialize curl handle
curl_setopt($ch, CURLOPT_URL, $url); //set the url
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); //return as a variable
curl_setopt($ch, CURLOPT_POST, 1); //set POST method
curl_setopt($ch, CURLOPT_POSTFIELDS, $request); //set the POST variables
$response = curl_exec($ch); //run the whole process and return the response
curl_close($ch); //close the curl handle
//print $response; //show the result onscreen for debugging
?>


First, we initialize a new CURL session. Then we set our desired options; this includes setting CURLOPT_POST because TM4B's SMS API requires us to send multiple messages using POST. Finally we execute the call and then close the handle.

Sending the Request with Sockets

CURL functions depend on an external library and PHP must have been compiled with the --with-curl flag. So while CURL is very flexible and useful, it may not be available with your PHP installation. If this is the case, you can still communicate with the SMS gateway using sockets.


<?php
//First prepare the info that relates to the connection
$host = "tm4b.com";
$script = "/client/api/send.php";
$request_length = strlen($request);
$method = "POST"; // must be POST if sending multiple messages
if ($method == "GET")
{
$script .= "?$request";
}
//Now comes the header which we are going to post.
$header = "$method $script HTTP/1.1\r\n";
$header .= "Host: $host\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: $request_length\r\n";
$header .= "Connection: close\r\n\r\n";
$header .= "$request\r\n";

//Now we open up the connection
$socket = @fsockopen($host, 80, $errno, $errstr);
if (
$socket) //if its open, then...
{
fputs($socket, $header); // send the details over
while(!feof($socket))
{
$output[] = fgets($socket); //get the results
}
fclose($socket);
}
/* the message id's will be kept in one of the $output values
print "";
print_r($output);
print "";
*/
?>


First we layout the information we'll need to send our SMS and use it construct the HTTP header. A socket connection is established to our gateway using fsockopen. Information is sent and received in the same manner PHP would read and write to a file. After our transfer is complete we close the socket using fclose.

Conclusion

That's It! Although it took me a long time to find CURL, I think it is the best, neatest and quickest option assuming your version of PHP supports it. Furthermore, whilst both fsockopen and CURL can send thousands of messages in one go, fsockopen might give you difficulties when parsing responses for large requests as the responses are transferred in chunks.

The above took me ages; I hope it saves you time.

Farheen
www.bestkeptsimple.org









Watching The Web
Categories : PHP, Databases, MySQL, HTTP, MD5
Referer Statistics
Categories : PHP, MySQL, HTTP, Databases
Protecting PHP Scripts with HTTP Authorization
Categories : PHP, HTTP, Security, Authentication
Writing A Port Scanner In PHP
Categories : PHP, HTTP, Security
Uploading files to the server with PHP
Categories : PHP, File System, HTML and PHP, HTTP
tracking where and what on your site people are clicking
Categories : PHP, MySQL, HTML and PHP, HTML
Installing PHP Under Personal Web Server
Categories : Personal Web Server (PWS), PHP, Web Servers, Installation
Miles To Go Before I Sleep...
Categories : PHP, Calendar, Databases, MySQL
Building Cross Platform GUI Apps With PHP-GTK
Categories : PHP, PHP-GTK, GUI Apps
Time Is Money Part 1 of 2 - Designing and implementing a Web-based application
Categories : PHP, Databases, MySQL, Complete Programs
Alternating row colors with PHP and mySQL
Categories : PHP, Databases, MySQL, HTML and PHP
Multicolumn Output from a Database with PHP
Categories : PHP, Databases, HTML and PHP, MySQL
Jump Start to Easy URLs
Categories : PHP, Beginner Guides, MySQL, File System, To PHP
Using Adobe's Flex Builder tool to connect a PHP backend to the front end
Categories : PHP, Macromedia Flex
Array Manipulation With PHP
Categories : PHP, Arrays