Tuesday, 26 March 2013

how-to-send-text-messages-with-php


How to Send Text Messages with PHP

Text messaging has become extremely widespread throughout the world — to the point where an increasing number of web applications have integrated SMS to notify users of events, sales or coupons directly through their mobile devices.
In the following tutorial, we will cover the fundamentals of sending text messages with PHP.

Below is a simplified diagram of how a message can be sent from a web application to a wireless device.  


We’ll break this down — one piece at a time:
  • The message is composed using a web application that is stored and executed on a HTTP server and then sent through the internet (“the cloud”) as an email message.
  • The email is received by a Short Message Service Gateway (SMS Gateway), which converts the message from an email message to a SMS message.
  • The SMS message is then handed to a Short Message Service Center (SMSC), which is a server that routes data to specific mobile devices.
  • The message is finally transmitted over the wireless network to the recipient.
Most wireless networks have a SMS gateway through which email messages can be sent as text messages to a mobile device. This is nice, because, from a developer’s standpoint, it is generally free—however, it is of course not a free service for the end user. Fees still apply to the recipient of the message and messages sent via email will be billed as a non-network text message.

EMAIL TO SMS

To send a SMS via email, you’ll generally require only two things: 
  • The phone number or unique identifier of the mobile device you want to reach.
  • And the wireless network’s domain name (many can be found in this list of email to SMS addresses)
The following convention can be followed for most carriers: 

phoneNumber@domainName.com

phoneNumber is the phone number of the mobile device to send the message to, and domainName.com is the address for the network’s SMS Gateway.

To send a text to Mr. Example, you could simply add 3855550168@vtext.com to any email client, type a message and hit send. This will send a text message to phone number +1 (385) 555-0168 on the Verizon Wireless Network.


For example, I’ll send a text message to myself using Gmail.


When my phone receives the message, it should look like so:

PHP’S MAIL FUNCTION 

LET’S TAKE THINGS A STEP FURTHER. USING THE SMS GATEWAY, WE CAN SEND A TEXT MESSAGE VIA EMAIL USING PHP’S MAIL FUNCTION. THE MAIL FUNCTION HAS THE FOLLOWING SIGNATURE: 

BOOL MAIL ( STRING $TO , STRING $SUBJECT , STRING $MESSAGE [, STRING $ADDITIONAL_HEADERS [, STRING $ADDITIONAL_PARAMETERS ]] )

You can read more about it here.
  • $to defines the receiver or receivers of the message. Valid examples include:
    • user@example.com
    • user1@example.com, user2@example.com
    • User <user@example.com>
    • User1 <user1@example.com>, User2 <user2@example.com>
  • $subject is rather self explanatory; it should be a string containing the desired subject. However, SMS do not require a subject.
  • $message is the message to be delivered. As mentioned in the PHP manual, “each line should be separated with a LF (\n). Lines should not be larger than 70 characters.”
To replicate the earlier functionality, we could write the following PHP code:

mail( '3855550168@vtext.com''''Testing' );

A TEST DRIVE 

LET’S RUN A TEST WITH PHP TO MAKE THAT SURE EVERYTHING IS SETUP CORRECTLY AND THAT THE MAILFUNCTION WILL, IN FACT, SEND A TEXT MESSAGE. USING THE FOLLOWING CODE, WE CAN RUN:  

VAR_DUMP( MAIL( '##########@VTEXT.COM''''THIS WAS SENT WITH PHP.' ) ); // BOOL(TRUE)  

WHEN MY PHONE RECEIVES THE MESSAGE, IT LOOKS LIKE SO: 

AS YOU CAN SEE IN THE IMAGE ABOVE, THE MESSAGE SHOWS THAT IT IS FROM GMAIL. THIS IS BECAUSE I ROUTE ALL MY OUTGOING MESSAGES FROM MY LOCAL SERVER THROUGH THAT SERVICE. UNFORTUNATELY, AS OF THIS WRITING, I HAVE BEEN UNSUCCESSFUL AT ALTERING THE FROM HEADER TO REFLECT AN ALTERNATE ADDRESS. IT SEEMS THAT THE EMAIL HEADERS ARE STRIPPED AND REPLACED WITH HEADERS PREPARED BY THE SMS GATEWAY. IF ANYONE KNOWS OF A WORKAROUND, PLEASE LEAVE A COMMENT AND LET THE REST OF US KNOW!

ADDING USABILITY

The Markup

With the basics out of the way, let’s take this idea and wrap a user interface around it. First we’ll set up a simple form:

<!DOCTYPE html>
 <head>
   <meta charset="utf-8" />
  </head>
  <body>
   <div id="container">
    <h1>Sending SMS with PHP</h1>
    <form action="" method="post">
     <ul>
      <li>
       <label for="phoneNumber">Phone Number</label>
       <input type="text" name="phoneNumber" id="phoneNumber" placeholder="3855550168" /></li>
      <li>
      <label for="carrier">Carrier</label>
       <input type="text" name="carrier" id="carrier" />
      </li>
      <li>
       <label for="smsMessage">Message</label>
       <textarea name="smsMessage" id="smsMessage" cols="45" rows="15"></textarea>
      </li>
     <li><input type="submit" name="sendMessage" id="sendMessage" value="Send Message" /></li>
    </ul>
   </form>
  </div>
 </body>

The Style

Next we’ll sprinkle in some CSS:

body {
 margin: 0;
 padding: 3em 0;
 color: #fff;
 background: #0080d2;
 font-family: Georgia, Times New Roman, serif;
}

#container {
 width: 600px;
 background: #fff;
 color: #555;
 border: 3px solid #ccc;
 -webkit-border-radius: 10px;
 -moz-border-radius: 10px;
 -ms-border-radius: 10px;
 border-radius: 10px;
 border-top: 3px solid #ddd;
 padding: 1em 2em;
 margin: 0 auto;
 -webkit-box-shadow: 3px 7px 5px #000;
 -moz-box-shadow: 3px 7px 5px #000;
 -ms-box-shadow: 3px 7px 5px #000;
 box-shadow: 3px 7px 5px #000;
}

ul {
 list-style: none;
 padding: 0;
}

ul > li {
 padding: 0.12em 1em
}

label {
 display: block;
 float: left;
 width: 130px;
}

input, textarea {
 font-family: Georgia, Serif;
}

This gives us the following simple form: 


THE SCRIPT

The most important part to this is the PHP script. We’ll write that bit of code now: 

<?php

if ( isset( $_REQUEST ) && !empty( $_REQUEST ) ) {
 if (
 isset( $_REQUEST['phoneNumber'], $_REQUEST['carrier'], $_REQUEST['smsMessage'] ) &&
  !empty( $_REQUEST['phoneNumber'] ) &&
  !empty( $_REQUEST['carrier'] )
 ) {
  $message = wordwrap( $_REQUEST['smsMessage'], 70 );
  $to = $_REQUEST['phoneNumber'] . '@' . $_REQUEST['carrier'];
  $result = @mail( $to, '', $message );
  print 'Message was sent to ' . $to;
 } else {
  print 'Not all information was submitted.';
 }
}

?>
<!DOCTYPE html>

  • The script first checks to see if the form has been submitted.
  • If yes, it checks to see if the phoneNumbercarrier and smsMessage variables were sent. This is useful in the case where there may be more than one form on the page.
  • If phoneNumbercarrier and smsMessage are available and phoneNumber and carrier are not empty, it is okay to attempt to send the message.
  • The message argument in the mail function should be 70 characters in length per line. We can chop the message into 70 character chunks using the wordwrap function.
  • phoneNumber and carrier are concatenated and then the message is sent using the mail function.
  • If data is missing or it cannot be validated, the script simply returns Not all information was submitted.
  • Finally, mail returns a boolean indicating whether it was successful or not. The value is stored in $result in case I needed to verify that the message was in fact sent.
Note: The mail method only notifies whether the message was sent or not. It does not provide a way to check to see if the message was successfully received by the recipient server or mailbox.

THE FINAL CODE

 <?php

if ( isset( $_REQUEST ) && !empty( $_REQUEST ) ) {
 if (
 isset( $_REQUEST['phoneNumber'], $_REQUEST['carrier'], $_REQUEST['smsMessage'] ) &&
  !empty( $_REQUEST['phoneNumber'] ) &&
  !empty( $_REQUEST['carrier'] )
 ) {
  $message = wordwrap( $_REQUEST['smsMessage'], 70 );
  $to = $_REQUEST['phoneNumber'] . '@' . $_REQUEST['carrier'];
  $result = @mail( $to, '', $message );
  print 'Message was sent to ' . $to;
 } else {
  print 'Not all information was submitted.';
 }
}
?>
<!DOCTYPE html>
 <head>
   <meta charset="utf-8" />
   <style>
    body {
     margin: 0;
     padding: 3em 0;
     color: #fff;
     background: #0080d2;
     font-family: Georgia, Times New Roman, serif;
    }

    #container {
     width: 600px;
     background: #fff;
     color: #555;
     border: 3px solid #ccc;
     -webkit-border-radius: 10px;
     -moz-border-radius: 10px;
     -ms-border-radius: 10px;
     border-radius: 10px;
     border-top: 3px solid #ddd;
     padding: 1em 2em;
     margin: 0 auto;
     -webkit-box-shadow: 3px 7px 5px #000;
     -moz-box-shadow: 3px 7px 5px #000;
     -ms-box-shadow: 3px 7px 5px #000;
     box-shadow: 3px 7px 5px #000;
    }

    ul {
     list-style: none;
     padding: 0;
    }

    ul > li {
     padding: 0.12em 1em
    }

    label {
     display: block;
     float: left;
     width: 130px;
    }

    input, textarea {
     font-family: Georgia, Serif;
    }
   </style>
  </head>
  <body>
   <div id="container">
    <h1>Sending SMS with PHP</h1>
    <form action="" method="post">
     <ul>
      <li>
       <label for="phoneNumber">Phone Number</label>
       <input type="text" name="phoneNumber" id="phoneNumber" placeholder="3855550168" /></li>
      <li>
      <label for="carrier">Carrier</label>
       <input type="text" name="carrier" id="carrier" />
      </li>
      <li>
       <label for="smsMessage">Message</label>
       <textarea name="smsMessage" id="smsMessage" cols="45" rows="15"></textarea>
      </li>
     <li><input type="submit" name="sendMessage" id="sendMessage" value="Send Message" /></li>
    </ul>
   </form>
  </div>
 </body>
</html>

1 comment:

  1. SMS API PHP has become one of the most important advertising tools that will surely be going to help in promotions of your business products and services. This API can be integrated with your website, software, or with any other applications.

    ReplyDelete