How to send SMS from a website using PHP and MySQL

download full project MySQL-PHP5-SMS-API-Example.zip (2.2 kB)

Introduction

This article is about sending SMS using PHP through MySQL Server. It is intended for web developers with a basic knowledge of the PHP and SQL technologies. The page contains a downloadable source code (see above), a list of aims you can achieve using the code, a list of prerequisites, a description and depiction of the architecture and operation of the system, step-by-step instructions about how to use the code and a detailed interpretation. It also includes a brief summary, answers to frequently asked questions, as well as links to related information.

When to use this code

This code is particularly useful for those who wish to

  • add SMS functionality to a website.
  • add SMS functionality to a corporate Intranet.
  • create automated SMS notifications.
  • increase website security by adding SMS login.

Prerequisites

The following table gives you a checklist on what you need to add SMS functionality to your MySQL enabled PHP website.

PHP host: Operating system: Linux or Windows
Webserver (Apache, or IIS)
PHP
MySQL Server
SMS Gateway host: Operating system: Windows or Linux
.NET framework (if you use Windows) or Mono (if you use Linux)
Ozeki NG-SMS gateway

Ozeki NG SMS Gateway can be obtained by
opening the download page:
Download Ozeki NG SMS Gateway!

How it works

To send SMS messages from PHP applications, you need to install Ozeki NG SMS Gateway and Microsoft SQL Server on your computer. Ozeki NG - SMS Gateway will use a GSM phone/modem attached to your PC (with a phone-to-PC data cable) or an IP SMS connection to send messages. Your PHP application will insert a row into the database to send messages using the Ozeki NG program. For a better understanding of how it works, please look at the following diagram (Figure 1).

how to send an sms from php sms api through a mysql server
Figure 1 - Sending SMS from PHP SMS API through a MySQL database server

In the diagram you can see an Internet user, a web server with the PHP application, an SQL Server, Ozeki NG - SMS Gateway, a mobile phone attached to the server computer and a mobile user receiving the message. Wherever the Internet user is, if they know the IP address or URL of the computer running the PHP script, and if they are authorized to log in, they can compose and send messages to any recipients.

After the Internet user's action, the PHP application inserts a row with the data of the SMS to be sent, which will be selected by Ozeki NG - SMS Gateway from the database. Ozeki NG will forward the message to the GSM network through a mobile phone attached to the PC with a data cable, and the mobile user will receive the SMS message.

Create a user and a database in MySQL

To find out how, check out the MySQL create table script page.

Create a Database user in Ozeki NG - SMS Gateway

Step 1: Open Ozeki NG's graphical user interface (Start menu -> All Programs -> OzekiNG -> Manage OzekiNG). Picture help

Step 2: Create the database user in Ozeki NG with the necessary data following the instructions.

Using the code

To use the downloaded PHP code, follow these steps:

Step 1: Unpack the downloaded zip file.
Step 2: Copy the sqlsmshandling.php, sqlsmshandling_inoutmessages.php and sqlsmshandling_functions.php files into the main directory of the Web Server.
Step 3: Set/Change the fixed data in the sqlsmshandling_functions.php file (e.g., server name, user name, password). Picture help
Step 4: Start the Ozeki NG - SMS Gateway Server (if not running). Picture help
Step 5: Start a web browser application (IE, Firefox, etc.) and enter this: http://127.0.0.1/sqlsmshandling.php (127.0.0.1 means that the copied example files reside on the same computer on which the browser has been opened). Picture help
Step 6: Fill in the necessary fields, and then click the "Send" button. Picture help
Step 7: Verify the message has been sent by Ozeki NG - SMS Gateway. Picture help

Understanding the code

The downloadable sample script inserts the message to be sent into the ozekimessageout database table. Ozeki NG - SMS Gateway periodically checks the table, and if it finds a row where the status is send, then it will try to send it. Inside the script you have to set the server name to where the MySQL Server is running, the username (specifying who can log in to the MySQL Server) with the password and the type of the SMS message.

The source code of the example application is structured in the following way:

sqlsmshandling.php:

This file contains page builder asp elements (text boxes, labels, etc.) and calls an insert function.

sqlsmshandling_functions.php:


   connectToDatabase(): connects to the MySQL Server and opens the database.
   closeConnection (): closes the connection.
   insertMessage (...): inserts the message to the outgoing database table.
   showOutgoingMessagesInTable(): selects the messages from ozekimessageout database table and shows it.
   showIncomingMessagesInTable(): selects the messages from ozekimessagein database table and shows it.
   sqlsmshandling_inoutmessages.php:
   builds the page that shows the message tables.

Description of the process depicted in Figure 1 above:

Step 1: Create the HTML form

In the sqlsmshandling.php file, you create the form that requests the sms data and shows a frame for tables incoming and outgoing messages. The Internet user fills in the necessaries. Label and textbox pairs will be displayed. Labels identify the requested data for the Internet user, and they will type it in textboxes. The user will be asked to fill in the Recipient and Message text fields.

sqlsmshandling.php

...
Compose message

Recipient:
Message text:
...
...

Inside the last table row (<tr>) you perform the sending of the message, as well as the notification of the Internet user in case of an error.

...
<?php

    if (isset($_POST["textAreaRecipient"]) && $_POST["textAreaRecipient"] == "")
    {
        echo "Recipient field mustn't be empty!";
    }
    else if (isset($_POST["textAreaRecipient"]) && $_POST["textAreaRecipient"] != "")
    {
    try
    {
        connectToDatabase();
        if (insertMessage ($_POST["textAreaRecipient"], "SMS:TEXT", $_POST["textAreaMessage"]))
        {
            echo "Insert was successful!";
        }
        closeConnection ();
    }
    catch (Exception $exc)
    {
        echo "Error: " . $exc->getMessage();
    }
}

?>
...


Step 2: Processing data coming from the HTML form

After filling in the fields and clicking the Send button, the Web server receives the information about the form. At the beginning of the php script, check the data of the textbox fields. The Recipient box is mandatory. If it is empty, the processing will be aborted, and the Internet user will be informed about the error. If the checking is successful, you will insert a new row into the ozekimessageout database table (in insertMessage (...)). You need the following: the address of the computer running the MySQL Server [the default address is localhost (localhost means that the MyQL Server is installed on the same computer on which the PHP script is running)], the username (who is authorized to log in to the MySQL Server and to insert messages, the user's password, the message type (the default is SMS:TEXT), the recipient and the message data.


sqlsmshandling_functions.php
...
function insertMessage ($recipient, $messageType, $messageText)
{
    $query = "insert into ozekimessageout (receiver,msgtype,msg,status) ";
    $query .= "values ('" . $recipient . "', '" . $messageType . "', '" . $messageText . "', 'send');";
    $result = mysql_query($query);
    if (!$result)
    {
        echo (mysql_error() . "
"); return false; } return true; } ...


Step 3: Checking the incoming and the outgoing message tables

By refreshing the table of incoming and outgoing messages, you can check the incoming messages and the status of outgoing messages. Look at the showOutgoingMessagesInTable() function. You will refill the outgoing messages table.


sqlsmshandling_functions.php
...
function showOutgoingMessagesInTable()
{
    $query = "select id,sender,receiver,senttime,receivedtime,operator,status,msgtype,msg from ozekimessageout;";
    $result = mysql_query($query);
    if (!$result)
    {
        echo (mysql_error() . "<br>");
        return false;
    }

    try
    {
        echo "<table border='1'>";
        echo "<tr><td>ID</td><td>Sender</td><td>Receiver</td>
        <td>Sent time</td><td>Received time</td><td>Operator</td>";
        echo "<td>Status</td><td>Message type</td><td>Message text</td></tr>";
        while ($row = mysql_fetch_assoc($result))
        {
            echo "<tr>";

            echo "<td>" . $row["id"] . "</td>";
            echo "<td>" . $row["sender"] . "</td>";
            echo "<td>" . $row["receiver"] . "</td>";
            echo "<td>" . $row["senttime"] . "</td>";
            echo "<td>" . $row["receivedtime"] . "</td>";
            echo "<td>" . $row["operator"] . "</td>";
            echo "<td>" . $row["status"] . "</td>";
            echo "<td>" . $row["msgtype"] . "</td>";
            echo "<td>" . $row["msg"] . "</td>";

            echo "</tr>";
        }
        echo "</table>";
        mysql_free_result($result);
    }
    catch (Exception $exc)
    {
        echo (mysql_error() . "<br>");
        return false;
    }

    return true;
}
...

Summary

In the article it has been explained how you can add SMS functionality to your website by using the downloadable PHP example code. You can freely use and modify that script. Using PHP scripts (and the Ozeki NG - SMS Gateway Server) you can create a lot of useful services(e.g.: you can add SMS functionality to a website or a corporate Intranet, create automated SMS notifications, increase website security by adding SMS login, etc.).

Frequently asked questions

Question: How can I send different message types?
Answer: For example, a Wap push message (in the insertMessage(...) function):
...
$query .= "values ('" . $recipient . "', 'SMS:WAPPUSH', '" . $messageText . "', 'send');";
...
$messageText format will be the following:



text of description



The action can be one of the following: signal-high, signal-medium, signal-low, signal-none, signal-delete.

Question: Can I run the PHP script on a computer different from the one running the Ozeki NG - SMS Gateway Server and the MySQL Server?
Answer: Yes, you can. In the script you have to set the Server name of the computer running the MySQL Server.

Question: Can I set the phone number so that the recipient can see where the sms comes from?
Answer: Yes, you can. In the script you have to set the sender field too. It works only if you have IP SMS connection.
   
...
$query = "insert into ozekimessageout (sender,receiver,msgtype,msg,status) ";
$query .= "values ('+449876543', '" . $recipient . "', '" . $messageType . "', '" . $messageText . "', 'send');";
...

More information