Tuesday, March 30, 2010

Sending SMS with PHP

ntroduction

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

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

1. 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.

2. 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∼=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:
//initialize the request variable
$request = "";
//this is the username of our TM4B account
$param["username"] = "abcdef";
//this is the password of our TM4B account
$param["password"] = "12345";
//this is the message that we want to send
$param["msg"] = "This is sample message.";
//these are the recipients of the message
$param["to"] = "447768254545|447956219273|447771514662";
//this is our sender
$param["from"] = "MyCompany";
//we want to send the message via first class
$param["route"] = "frst";
//we are only simulating a broadcast
$param["sim"] = "yes";
//traverse through each member of the param array
foreach($param as $key=>$val){
//we have to urlencode the values
$request.= $key."=".urlencode($val);
//append the ampersand (&) sign after each paramter/value pair
$request.= "&";
}
//remove the final ampersand sign from the request
$request = substr($request, 0, strlen($request)-1);

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∼=yes

3. 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.
//this is the url of the gateway's interface
$url = "http://www.tm4b.com/client/api/send.php";
//initialize curl handle
$ch = curl_init;
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
//show the result onscreen for debugging
//print $response;

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.

4. 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.
//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.1rn";
$header .= "Host: $hostrn";
$header .= "Content-Type: application/x-www-form-urlencodedrn";
$header .= "Content-Length: $request_lengthrn";
$header .= "Connection: closernrn";
$header .= "$requestrn";

//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.

5. 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.

Read more: http://www.webdesign.org/web-programming/php/sending-sms-with-php.14782.html#ixzz0jjEtZRSz

E-mail form using HTML and PHP

The first thing to do is create the form using html. We'll call it feedback.html. The form will have an action of send.php, which we'll create later. Below is the html code for our form:


E-mail Form


Name:

E-Mail Address:

Message:




Form Validation using PHP

Today I'll take it up a level and re-write that script using the if, else conditional and empty() function to include form validation.
Using an if, else conditional: if (condition) {do something} else { do this} , we can make certain fields of our form required that they be filled out. Let's start by making a basic form with first name, last name, email and comments as our text inputs. Copy the following code into a text document then save and name it form.html:




#form {
width: 500px;
margin-right: auto;
margin-left: auto;
}
->









Enter your information in the form below.

First Name:




Last Name:




E-Mail:




Comments:










The action for the form is the same as the last form tutorial (send.php) but we'll re-write it now to include the changes. The easiest way to check to see if a user has typed in a value in the text boxes is to use the empty() function. Using the old send.php the code looked like this for the Name variable: $msg = "Name; $_POST[name] "; . Using the empty() function and an if, else conditional to make sure the user typed in a value for the "first name" text box, the revised script is written like this:
if (!empty($_POST['fname'])){
$msg = "fname; $_POST[fname] ";
}else{
$fname = NULL;
echo "Please fill out your first name.
";
}
In the above script the empty() function checks to see if the "first name" box has a value. If yes, the value of the $fname variable would be sent to the recipients email. If the box is empty the $fname variable is set to NULL and the user sees the message "please fill out your first name" followed by a line break
. The " " that you see in the string simply adds a line break to the information being sent so that when the recipient receives the email, its not one continuous line.
So, the entire PHP script to check all text inputs is:

if (!empty($_POST['fname'])){
$msg = "fname; $_POST[fname] ";
}else{
$fname = NULL;
echo "Please fill out your first name.
";
}
if (!empty($_POST['lname'])){
$msg .= "lname: $_POST[lname] ";
}else{
$lname = NULL;
echo "Please fill out your last name.
";
}
if (!empty($_POST['email'])){
$msg .= "email: $_POST[email] ";
}else{
$email = NULL;
echo "Please leave your email address.
";
}
if (!empty($_POST['comments'])){
$msg .= "comments: $_POST[comments] ";
}else{
$comments = NULL;
echo "You forgot to leave a comment.
";
}
$recipient = "yourname@yourdomain.com";
$subject = "Form Feedback";
$mailheaders = "Reply-to: $_POST[email]";

//send the mail

mail($recipient, $subject, $msg, $mailheaders);

?>
Put this between the body tags of a new html document (make sure to change the $recipient to your email address) then save and name it send.php . Style the form.html to match your website then upload both the form.html and send.php to your server in the same directory you keep all of your other web site pages, and your done.

Configure a virtual directory using WAMP

As a web developer many want to test their developments on their local machines. But when it comes to dealing with PHP and MySQL you will need a web server (software) to test the sites you make. Normally we would have to download Apache from www.apache.org , MySQL from MySQL.net and configure these separately to work with each other on our local machine. Also if you want to administer MySQL on the browser you will have to install PHPMyAdmin which is a burden for the novice user.
To tackle these problems there are several packaged solutions on the net. Popular and more robust one is WAMP server. www.wampserver.com .
Let see step by step on how to create a root folder for our new web site that has to be built using PHP.
Step 1: Easiest way!
After installing WAMP on your local machine (You should see a white Speedo meter on the notification area) goes the folder where WAMP resides (If you install it on you C: partition then it is C:/wamp/). The folder structure is as follows,
Configure a virtual directory using WAMP image 1
Go inside the www folder and create a new folder inside it called "TestSite". This is the rot folder of your web site. Better if you do not put spaces. Open up a simple notepad document and insert the following on it (don't copy the formatting. Just type it),
Then same it inside the newly created folder and name it index.php.
Go to your browser and call http://localhost/TestSite/
If you see something like this then you are ready to do building rest of your dynamic web site.
Configure a virtual directory using WAMP image 2
Step2: Assigning a root folder outside "www".
Well, if we want separate our web site folders from the WAMP server folder and put somewhere else in the hard drive then procedure gets a bit tricky for the beginners.
First create the folder you want as the web site root folder. Let's say D:/MyNewTest/
Now we have to tell the WAMP server that this folder contains a web site and it should come up when the URL is called through the browser right?
Ok, first click on the little Speedometer icon on the notification area. Then go to,
Apache > Alias directories > Add an alias
Configure a virtual directory using WAMP image 3
Then you will be asked to give an alias to the site, this is what you type after http://localhost/ in the browser. Previous one was "TestSite" which is actually the folder name itself. But this is not necessary in this case. You can put anything. But don't use spaces or dots. J
Configure a virtual directory using WAMP image 4
Let's put "MySite".
Configure a virtual directory using WAMP image 5
Then you will be asked what is the actual folder that MySite alias point to.
Configure a virtual directory using WAMP image 6
Give the following, D:/MyNewTest/
Note the forward slashes.
Configure a virtual directory using WAMP image 7
Now press enter to close the DOS prompt.
Go to your browser and type the http://localhost/MySite/
You will see the root index now. Put the notepad file we created earlier to "D:/MyNewTest"and refresh the browser page to test the PHP.
That is it. Simple isn't it?

Displaying RSS Feeds in Text

Good afternoon everyone, today il be taking you through the steps of modifying your feed count. Ive had loads of e-mails asking how i designed my "stay connected" box and how i displayed my RSS count as pure text and not a feed burner image.
To display your feedburner RSS count as text we need to just add two snippets of code to our website. Open up a blank notepad document copy and paste the code below.
//get feedburner count
$whaturl="https://feedburner.google.com/api/awareness/1.0/GetFeedData?uri=hvdesigns";

//Initialize the Curl session
$ch = curl_init();

//Set curl to return the data instead of printing it to the browser.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

//Set the URL
curl_setopt($ch, CURLOPT_URL, $whaturl);

//Execute the fetch
$data = curl_exec($ch);

//Close the connection
curl_close($ch);
$xml = new SimpleXMLElement($data);
$fb = $xml->feed->entry['circulation'];
//end get feedburner count
Where "hv-designs" is in the 1st bif of code, change that to your feed. Save the blank notepad document as "rss.php", save it in the root of your websites directory. Now copy and paste the code below.
Paste it any where inside the body of your website. Now all you need to do is add the code below.
Then paste it inside your website where you want the RSS count to be.