How to Send Text Messages with PHP

How to Send Text Messages with PHP

Tutorial Details
  • Language: PHP
  • Difficulty: Beginner
  • Estimationed Completion Time: 30 minutes

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 this tutorial, we will cover the fundamentals of sending text messages with PHP.


Overview

Sending a text message (SMS) message is actually pretty easy.

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:

Pretty awesome!


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 mail function will, in fact, send a text message. Using the following code, we can run:

<?php

var_dump( mail( '##########@vtext.com', '', 'This was sent with PHP.' ) ); // bool(true)

?>

When my phone receives the message, it looks like so:

If you are getting an error, see the troubleshooting section.

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

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 phoneNumber, carrier and smsMessage variables were sent. This is useful in the case where there may be more than one form on the page.
  • If phoneNumber, carrier 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>

Troubleshooting

Localhost Error

In order to use the mail function, you must have a mail server running. If you’re running this on a web host, you’re probably okay. But if you are unsure, I recommend talking to an administrator. This also holds true for personal machines. So if you get errors like..

Warning: mail() [function.mail]: Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set() in C:\wamp\www\sms\mail-test.php

…you will have to install and configure a mail server. This is out of the scope of this tutorial. However, if you are working on your local machine, switching to something like XAMPP might solve this problem. Alternatively, try installing Mercury Mail alongside WAMP, MAMP or on a LAMP (or SAMP or OAMP, etc.) system (that’s a lot of ‘AMPs’).

PHPMailer

Another option (which is the method I prefer) is to use PHPMailer. Below is an example of how to use PHPMailer to connect to Gmail’s SMTP server and send the message.

Using it is as simple as including a class in your script.

require 'class.phpmailer.php';

// Instantiate Class
$mail = new PHPMailer();

// Set up SMTP
$mail->IsSMTP();                // Sets up a SMTP connection
$mail->SMTPDebug  = 2;          // This will print debugging info
$mail->SMTPAuth = true;         // Connection with the SMTP does require authorization
$mail->SMTPSecure = "tls";      // Connect using a TLS connection
$mail->Host = "smtp.gmail.com";
$mail->Port = 587;
$mail->Encoding = '7bit';       // SMS uses 7-bit encoding

// Authentication
$mail->Username   = "email.address@gmail.com"; // Login
$mail->Password   = "password"; // Password

// Compose
$mail->Subject = "Testing";     // Subject (which isn't required)
$mail->Body = "Testing";        // Body of our message

// Send To
$mail->AddAddress( "##########@vtext.com" ); // Where to send it
var_dump( $mail->send() );      // Send!

This should print out something along the lines of:

It may take a little more to set up the connection depending on your situation. If you’re planning on using Gmail, Google has provided information on connecting.


Conclusion

There are a myriad of methods to accomplish the task of sending a SMS through a web application. This method is really meant for low volume messaging (most likely less than 1,000 text messages per month) and developers looking to get their feet wet without forking out cash. Other options include:

  • Using a SMS Gateway Provider

    • Doing a Google search will return plenty of options.
    • Most SMS gateway providers include an API for sending messages through a web application.
    • You can usually sign up for service for a reasonable price, assuming you are planning on sending at least 1,000 SMS message per month.
    • You can rent a short code number.
  • Using a GSM modem

    • This can be a costly and slow way to do it, since you have to buy a modem and have a contract with a wireless network
    • You will also have to use the AT (Hayes) command set.
  • Use a direct connection to a wireless network, which will require some strong negotiating and a whole lot of money.

This tutorial is in no way a comprehensive review of sending tex messages with PHP; but it should get you started! I hope this tutorial has been of interest to you. Thank you so much for reading!

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://ashish4design.wordpress.com/ Ashish

    wow…. thanks for this….

    • ashwin

      the best every system which i tried is http://weekwill.com

      Its works fast and easy! also its secure and reliable.

    • aksar

      chaabaaal

  • http://www.estiloyredaccion.com Ohdile

    Hello. It’s my first time here and I like so much your website, thank your for all the tutorials.

    I want to probe this but I don’t know if it will work in Peru.

    I’ll probe it anyways.

    Thanks again.

  • safeer khan

    hi,
    thanks for the tutorial .i am from pakistan. can i use the vtext sms gateway

  • g

    hmmmmmm………. interesting…. how could we
    no need to pay while sending sms ….. hmmm.

    How about, http://playsms.org/about-2/ ?

  • http://www.accentudate.com Paul

    Great tutorial…I’m going to add this functionality to my site :)

    Thanks,
    -Paul

  • http://www.accentudate.com Paul

    Is it possible to set the senders address? Basically I would like to provide this feature for users of my site but would require that each user enter and use their own email address so they can communicate directly with other members.

    Any insight would be appreciated.

    Thanks,
    -Paul

  • Cam

    Blah, I thought this would tell how to do it with out knowing the carrier.

    • josh

      Just send it to all of them.. let the bad ones bounce. Duh.

  • shravani

    Thank u so much.. It is of great help to us.

  • swati

    thank u…………………………..so much

  • MarvinR

    Geez..this is super cool, thanks a lot for the tutorial..May the Good God Bless You more….;)

  • http://www.earnonweblog.com anisur rahman

    Is it free to send message to mobile?

  • praveen dasari

    hai iam praveen i want to know how to send sms to various mobile using .net ….can you plse send the code to my email-id …….my email-id is vijaypraveen.friend212@gmail.com

  • http://03344760108 ali

    hy kya hal hai

  • Mark

    This works awesome!

    Just wondering if you have something that shows how you can receive an SMS message.

    Thanks.

  • Ron June Lopez

    SMTP -> FROM SERVER:220 mx.google.com ESMTP ml4sm9149588pbc.0
    SMTP -> FROM SERVER: 250-mx.google.com at your service, [58.69.239.170] 250-SIZE 35882577 250-8BITMIME 250-STARTTLS 250 ENHANCEDSTATUSCODES
    SMTP -> FROM SERVER:220 2.0.0 Ready to start TLS

    Warning: stream_socket_enable_crypto() [streams.crypto]: this stream does not support SSL/crypto in D:\xampp\htdocs\ronron\class.smtp.php on line 197

    - I have the problem with this

  • ziaziazia

    may i ask some question ?

    this format ->> phoneNumber@domainName.com

    is it domainName.com is smtp server ??

  • mesuk

    Thanks a lot for this tutorial. I am from Bangladesh.

    • elahi

      hello mesuk … i am also from bangladesh .. can you tell me any bangladeshi network domain name plz ..

  • http://about.me/butchewing Butch Ewing

    Great article! I am in the process of implementing this into my user authentication system. I found a neat little list of wireless network SMS gateway email addresses. You can download the e-mail to SMS providers list as SQL and CSV formats to SMS-enable your web applications quickly.

    http://www.uptimerobot.com/sms.asp

    • JR

      @Kevin – thanks for a nice intro into setting up simple SMS messages through PHP … nicely done.

      @Butch Ewing – thank you for the link to the list of mobile providers … it hits the spot for my current client project, and was the one item missing to round out this article.

      best.

      • Kay

        Great job on finding this list.

  • FaisalHafeez

    not working

  • Arun

    Could you please let me know what is carrier-field indicate in send sms script?

  • http://anthonyterrell.com Anthony Terrell

    Is there a way to remove the server information when you send the text message. This is great, but the message is so bulking on the receiving end.

    Thanks!

  • vasu

    codes are working but messages are not delivered

  • http://share-pcwallpapers.com rakesh

    Thank u so much.. It is of great help to us.

  • sonu sindhu

    nice scipt.It was vey helpful……..

  • KNIBIAAXOGALK

    Summerinaskinalk

  • vivek

    i have created a web page, which accept user details. i want the php code which sends text message and email automatically to user, using the information given by him/her…

    its like when your insurance is about to expire on 05-1-2012, and you will get an email and text message regarding the expiry on 02-1-2012…

    i will use sms gateway service to send text message. i want the code…

    please inform me as soon as possible…..

  • ner0

    Great tutorial.
    How can you join both techniques in order to use the form to pass the variables to PHP mailer?

  • http://goo.gl/5oyQb John Ortiz

    Thanks. It is perfectly working for me.

    • mehreen

      can u plz tell how it is working perfectly for u?
      there is no code error and message deliverd is also displayed but im not reciving the message in my mobile

  • bhosaleakshay2009

    my localhost is showing the error such like:-

    “SMTP -> FROM SERVER:220 mx.google.com ESMTP he16sm18900383ibb.9
    SMTP -> FROM SERVER: 250-mx.google.com at your service, [123.201.121.149] 250-SIZE 35882577 250-8BITMIME 250-AUTH LOGIN PLAIN XOAUTH 250-ENHANCEDSTATUSCODES 250 STARTTLS
    SMTP -> FROM SERVER:220 2.0.0 Ready to start TLS

    Warning: stream_socket_enable_crypto() [streams.crypto]: this stream does not support SSL/crypto in C:\Users\Akshay\Desktop\Tutorial\Akshay’s Blog Backup\mail_function\class.smtp.php on line 200″

    i’m newbie to this…
    n m not able to understand why is so….!!

    will you please help me..??

    regards,
    bhosaleakshay2009

  • Kay

    Thanks for your tutorial, it really helped.

  • Kay

    Thanks for your tutorial, it really helped.

  • http://www.aidanbw.co.uk Aidan BW (auto-b0t)

    I installed this on my server: http://www.aidanbw.co.uk , http://www.melvynvincent.com and http://www.watersmusic.co.uk .
    Works perfectly with slight adjustments to the script, thanks!! :-)

  • prudhvi

    Hi..
    I used mail like this

    if(mail( ‘XXXXXXXXXXXXX@airtelkk.com’, ”, ‘Hi Prudhvi’ ))
    echo “ok”;

    the out is :ok

    But the message is not coming to my mobile..

    As you listed some sms addresses. I used airtel karnataka(airtelkk.com)..

  • judah

    can i send this to a multiple recipients?

  • jak

    nice tuts… but my localhost the mail sent successful but i can’t receive message in my mobile

  • hali

    Hey, I am from Pakistan. Which SMS address could I use?

  • http://www.ryanbradley.com Ryan Bradley

    One of the best tutorials I’ve seen yet, very helpful.

  • http://8bc40bd6.seriousdeals.net Nigel Barksfield

    Great tutorial! But I want to do the opposite, and get SMS messages from cell phones and turn them into emails for my safelist.

    Any thoughts?

  • Aneeq

    To send HTML mail in PHP, you need to use some additional headers. Below is the code to send HTML mail in PHP.

    $to = “recipient@domain.com“;
    $subject= “Subject of email”;
    $message= “This is HTML mail.”;
    $fromName = “Name of the sender”;
    $fromEmail = “sender@domain.com“;

    // To send HTML mail, the Content-type header must be set
    $headers = “MIME-Version: 1.0? . “\r\n”;
    $headers .= “Content-type: text/html; charset=iso-8859-1? . “\r\n”;

    // Additional headers
    $headers .=”From: $fromName ”.”\r\n”;

    //Mail function
    mail($to, $subject, $message, $headers);

    Source:
    http://http://phphelp.co/2012/05/03/how-to-send-html-mail-in-php//

    OR

    http://http://addr.pk/a1c4

  • http://collegewires.com/android Hrishikesh Kumar

    This is cool. Awesome. Will try it someday.

  • http://www.vueine.com vueine

    This example is difficult, too slow to understand

  • http://www.ucmcommunication.com marketing télécom

    I’ve been browsing online more than 3 hours lately, yet I by no means discovered any fascinating article like yours. It is lovely price sufficient for me. In my view, if all webmasters and bloggers made just right content as you probably did, the internet shall be much more helpful than ever before.

  • http://www.Coroflot.com/RaihanMazumder Mohammad Raihan Mazumder

    Great Tutorial. Can i have this tutorial source file?

    Thanks in advance.

    Raihan
    Yogyakarta, Indonesia.
    Mob: +6281228866622

  • Sayan

    Not working sir.

    give this error.

    SMTP -> FROM SERVER:220 mx.google.com ESMTP ov8sm5150275pbb.2
    SMTP -> FROM SERVER: 250-mx.google.com at your service, [59.164.131.112] 250-SIZE 35882577 250-8BITMIME 250-AUTH LOGIN PLAIN XOAUTH 250-ENHANCEDSTATUSCODES 250 STARTTLS
    SMTP -> FROM SERVER:220 2.0.0 Ready to start TLS

    Warning: stream_socket_enable_crypto() [streams.crypto]: this stream does not support SSL/crypto in C:\xampp\htdocs\gibbons\smtp\class.smtp.php on line 197

    After correcting it….it gives another error….

    SMTP -> FROM SERVER:220 mx.google.com ESMTP nv6sm16362289pbc.42
    SMTP -> FROM SERVER: 250-mx.google.com at your service, [59.164.131.112] 250-SIZE 35882577 250-8BITMIME 250-AUTH LOGIN PLAIN XOAUTH 250-ENHANCEDSTATUSCODES 250 STARTTLS
    SMTP -> FROM SERVER:220 2.0.0 Ready to start TLS
    SMTP -> FROM SERVER:
    SMTP -> ERROR: EHLO not accepted from server:
    SMTP -> FROM SERVER:
    SMTP -> ERROR: HELO not accepted from server:

    Notice: fputs() [function.fputs]: send of 12 bytes failed with errno=10053 An established connection was aborted by the software in your host machine. in C:\xampp\htdocs\gibbons\smtp\class.smtp.php on line 212
    SMTP -> ERROR: AUTH not accepted from server:
    SMTP -> NOTICE: EOF caught while checking if connectedSMTP Error: Could not authenticate. bool(false)
    Message was sent to **********@sayandas07@gmail.com

    Please help me to overcome it.

  • http://www.naklejki-dekoracyjne.pl/ 4DECOR

    Thank you, I’ll try to implement this code on my webshop.

  • http://isms.com.my hpang

    1. Firstly, register a username and password from http://isms.com.my/​register.php. It only requires a few information and it is free. After you have register an account, you will need to purchase some credit from http://isms.com.my/​buy_reload.php, typically, you will receive an email containing the reload PIN if you purchase for the first time. However, if you purchase more than once, the account is automatic credited. Login to http://isms.com.my and load the PIN.

    2. For PHP, use the code below, replace all variables with relevant variables.

    $sendlink = “http://www.isms.com.my/​isms_send.php?un=”.($userna​me).”&pwd=”.($password).”&​dstno=”.$dstno.”&msg=”.url​encode($msg).”&type=”.$typ​e.”&sendid=”.$senderid;.
    fopen($sendlink, “r”);

    3. It just work!

  • elahi

    Is there anyone tell send me some bangladeshi network domain name ..

  • http://www.intrugs.com fazil

    This is wonderfull….But i have a doubt that what is carrier..is this like gmail,yahoo????please reply

  • hudson kotel

    I have a post in my forum any simple code for sending SMS using PHP please post here, thanks in advance http://www.phphunt.com/115/send-sms-in-php

  • sujoy

    I was trying to send sms via gmail using @aircel.co.in as i use aircel, but i received failed msg of delivery, I’ve checked it from my domain’s email account but I’ve received the same error msg. I’ven’t got any sms!!! why I’m getting this msg? I’ve DND activated on my mobile previously.