Howto Send/Read SMSs using a GSM modem, AT+ commands and PHP


I need to send/read SMS with PHP. To do that, I need a GSM modem. There are few of them if we google a little bit. GSM modems are similar than normal modems. They’ve got a SIM card and we can do the same things we can do with a mobile phone, but using AT and AT+ commands programmatically. That’s means we can send (and read) SMSs and create scripts to perform those operations. Normally those kind of devices uses a serial interface. So we need to connect our PC/server with a serial cable to the device. That’s a problem. Modern PCs sometimes dont’t have serial ports. Modern GSM modems have a USB port, and even we can use serial/USB converters. I don’t like to connect directly those devices to the PC/server. They must be close. Serial/USB cables cannot be very long (2 or 3 meters). I prefer to connect those devices using serial/ethernet converters. Because of that I will create a dual library. The idea is enable the operations when device is connected via serial cable and also when it’s connected thought a serial/ethernet converter.

The idea is the following one: We are going to create a main class called Sms. It takes in the constructor (via dependency injection) the HTTP wrapper or the serial one (both with the same interface). That means our Sms class will work exactly in the same way with one interface or another.

Let’s start. First we’re going to create a Dummy Mock object, sharing the same interface than the others. The purpose of that is to test the main class (Sms.php)

<?php
class Sms_Dummy implements Sms_Interface
{
    public function deviceOpen()
    {
    }

    public function deviceClose()
    {
    }

    public function sendMessage($msg)
    {
    }

    public function readPort()
    {
        return array("OK", array());
    }

    private $_validOutputs = array();

    public function setValidOutputs($validOutputs)
    {
        $this->_validOutputs = $validOutputs;
    }
}

And we test the code:

<?php

require_once('Sms.php');
require_once('Sms/Interface.php');
require_once('Sms/Dummy.php');

$pin = 1234;

$serial = new Sms_Dummy;

if (Sms::factory($serial)->insertPin($pin)
                ->sendSMS(555987654, "test Hi")) {
    echo "SMS sent\n";
} else {
    echo "SMS not Sent\n";
}

It works. Our Sms class sends a fake sms using Sms_Dummy

Now we only need to create Sms_Serial and Sms_Http. For Sms_Serial I’ve use the great library (with a slight modifications) of Rémy Sanchez to read/write serial port in PHP (you can find it here). We can run it with a script similar than the Dummy one, thanks to dependency injection:

require_once('Sms.php');
require_once('Sms/Interface.php');
require_once('Sms/Serial.php');

$pin = 1234;

try {
    $serial = new Sms_Serial;
    $serial->deviceSet("/dev/ttyS0");
    $serial->confBaudRate(9600);
    $serial->confParity('none');
    $serial->confCharacterLength(8);

    $sms = Sms::factory($serial)->insertPin($pin);

    if ($sms->sendSMS(555987654, "test Hi")) {
        echo "SMS sent\n";
    } else {
        echo "Sent Error\n";
    }

    // Now read inbox
    foreach ($sms->readInbox() as $in) {
        echo"tlfn: {$in['tlfn']} date: {$in['date']} {$in['hour']}\n{$in['msg']}\n";

        // now delete sms
        if ($sms->deleteSms($in['id'])) {
            echo "SMS Deleted\n";
        }
    }
} catch (Exception $e) {
    switch ($e->getCode()) {
        case Sms::EXCEPTION_NO_PIN:
            echo "PIN Not set\n";
            break;
        case Sms::EXCEPTION_PIN_ERROR:
            echo "PIN Incorrect\n";
            break;
        case Sms::EXCEPTION_SERVICE_NOT_IMPLEMENTED:
            echo "Service Not implemented\n";
            break;
        default:
            echo $e->getMessage();
    }
}

And finaly the Http one. As you can see the the script is the same than the Serial one. the only difference is the class passed to the constructor of the Sms class:

<?php 
require_once('Sms.php'); 
require_once('Sms/Interface.php'); 
require_once('Sms/Http.php'); 

$serialEternetConverterIP = '192.168.1.10'; 
$serialEternetConverterPort = 1113; 
$pin = 1234; 
try {
     $sms = Sms::factory(new Sms_Http($serialEternetConverterIP, $serialEternetConverterPort));
     $sms->insertPin($pin);

    if ($sms->sendSMS(555987654, "test Hi")) {
        echo "SMS Sent\n";
    } else {
        echo "Sent Error\n";
    }

    // Now read inbox
    foreach ($sms->readInbox() as $in) {
        echo"tlfn: {$in['tlfn']} date: {$in['date']} {$in['hour']}\n{$in['msg']}\n";

        // now delete sms
        if ($sms->deleteSms($in['id'])) {
            echo "SMS Deleted\n";
        }
    }
} catch (Exception $e) {
    switch ($e->getCode()) {
        case Sms::EXCEPTION_NO_PIN:
            echo "PIN Not set\n";
            break;
        case Sms::EXCEPTION_PIN_ERROR:
            echo "PIN Incorrect\n";
            break;
        case Sms::EXCEPTION_SERVICE_NOT_IMPLEMENTED:
            echo "Service Not implemented\n";
            break;
        default:
            echo $e->getMessage();
    }
}

Serial/Ethernet converters normally have different operational modes. They allow you to create a fake serial port on your PC and work exactly in the same way than if you have your device connected with a serial cable. I don’t like this operation mode. I prefer to use the TCP server mode. With the TCP server mode I can read/write from the serial device with the standard socket functions. So if you dive into Sms_Http class you will find TCP socket’s functions.

And finally I will do a brief excerpt of AT+ commands used to send /read SMSs:

AT+CPIN?\r : checks if SIM has the pin code. It answers +CPIN: READY or +CPIN: SIM PIN if we need to insert the pin number
AT+CMGS=”[number]”\r[text]Control-Z : to send a SMS (in php we have Control-Z with chr(26)). It returns OK or ERROR
AT+CMGF=1\r: set the device to operate in SMS text mode (0=PDU mode and 1=text mode). Returns OK.
AT+CMGL=\”ALL”\r read all the sms stored in the device. We also can use “REC UNREAD” Instead of “ALL”.
AT+CMGD=[ID]\r: Deletes a SMS from the device

You can download the source code from github here

127 thoughts on “Howto Send/Read SMSs using a GSM modem, AT+ commands and PHP

    1. It works, indeed 🙂 (I use it) The serial version works only in Linux, but the http version should work in windows too (I don’t use Windows so I cannot test it).

      1. As I said before I’m not Windows user, so I cannot test it. The original library works with ws (you can see the link in the post), but I removed the windows support because I will not use it. MAybe you can hack a little bit an add the windows support. Anyway I recommend the HTTP interface (with a serial-ethernet adapter) that works with any OS

  1. Nice tuto. Someday I will try.
    Do you recommend any specific modem or serial-ethernet converter?

    Thank you very much.
    Marcos
    Brazil

      1. Thank you Gonzalo.

        I am trying to develop a php system (with google maps) that will receive SMS messagens from a GPS tracker.
        For now I am gathering all necessary information.

        Let me explain my idea:
        – make a server (with this GSM modem you recomended) that receive data from all trackers we have.
        – using php, show that information trought our intranet.

        What do you thing about the idea?
        I know there must be something similar, but if I can not pay, I can try.

        Do you have any recomendation?

        Ps.: your name seems to be something latin.

        Best regards from Brazil
        Marcos

  2. Hi Gonzalo, great piece of work here!
    I am going to test it this evening, so I will return here posting my observations.
    Have you ever considered releasing it under GPL license and build a more complex software around it? Maybe even a ncurses UI, not to tell about GTK.
    But enough with dreaming, I’ll come back with further comments.
    Thanks and keep up the good work!

    1. It will be cool it this library helps you in your instalation.

      I’m not a licence expert. If it’s necesary to change it to create open source projects it will be changed. My aim is to share the code with the community (in fact it’s based to an open source library).

    1. If you use the serial-ethernet conversor, the script probably work as-is on Windows environment (not sure, not tested), but if you connect the GSM moden with the serial port, have a look to the original class http://www.phpclasses.org/package/3679-PHP-Communicate-with-a-serial-port.html. As I can read, it works with windows. Anyway I didn’t test it. My Sms_Serial class is almost identical than original one. Without windows support and with slight differences when reading the serial port.

      1. Actually i alreay used the the php class u mentioned.

        When i use the class, (i also used the fopen() function to open the communication port on windows) , first it god connected for both read and write operation.

        But when i sent the AT command using fwrite the modem got hanged and when i restarted the modem, i got error “Cannot open the port. Access Denied.”

        I am not sure what the problem is but its not letting me to do any thing except opening the port.

        Might be u know anything regarding this?

        Your help is greatly appriciated.

        Regards,
        Rajendra Pondel.

    2. “Cannot open the port. Access Denied.” means your script is still using the port. This’s probably because is trying to read the buffer from the serial port. I changed the original serial class because a similar issue. If you see the differences between the original one and my version, the read function is different (y read one byte instead to waiting to end of the line). Try to echo the buffer to see if you read text from sms (check the leds of the modem to see it it’s sending data to)

  3. I’m using the testHTTP.php example on my nport Moxa serial/ip unit.

    It works perfect!

    Additional question :

    How to receive or send concatenated messages? As I’m seeeing long sms is not shown well in the screen. I see strange signs and messages are splitted …

    Thx for the help!

    Regards,

    Jaan Colman

    1. Btw, for example :

      [msg] => ‚@oH. @In Belgie gelden de volgende tarieven: bellen naar NL en binnen EU 51ct p/m. Gebeld worden altijd 23ct p/m.112 is gratis. Sms is 13ct, sms ontvangen is g

      [msg] => ‚@oH.­@ratis! Goede reis, KPN. Geen tarief berichten meer ontvangen bij de grens? SMS ‘INFO UIT’ naar 1330.

      In fact the original message needs to be :

      Hi! In Belgie gelden de volgende tarieven : bellen naar NL en binnen EU 51ct p/m. Gebeld worden altijd 23ct p/m. 112 is gratis. Sms is 13ct, sms ontvangen is gratis! Goede reis, KPN etc …

      I see in the beginning of both messages strange signs …

      Thx!

      1. AFAIK if you want to send concatenated sms you need to do it in an extra layer Check the length and split the mesage into separeted sms before send it to the modem.

        Take care with non ascii strings. gsm modems work with gsm encoding (not the same than utf8) http://en.wikipedia.org/wiki/GSM_03.38. I normally send ascii sms, I’m not sure how to encode text to gsm encoding with php. I’ve looking for any solution in google and stack overflow and I didn’t find a good solution. But I think your problems are because this issue

  4. Hi,

    It must be perfectly possible to encode/decode a pdu string in php …

    I’m finding that out now and coming back to this …

    Thx for tip!

    Regards,

    Jaan Colman

    1. Problably will work without pin. I can test it with a real modem now. You need to put:
      $sms->insertPin(null); or $sms->insertPin(”);

    1. Sorry. But as I said in previous comments I haven’t any windows system to test it. You need to hack Sms_Serial class to enable windows support. I normally use Ethernet converters and linux.

    2. I’m afraid I cannot help you with windows. As I said in a previous comment have a look to the original class http://www.phpclasses.org/package/3679-PHP-Communicate-with-a-serial-port.html. As I can read, it works with windows. You will see Sms_Serial is very similar to the original one. I drop windows support (I cannot test it) and I also change a little bit the original way to read from the serial port because the original one doesn’t work with my devices (I don’t really know why)

    1. If your SIM card doesn’t have a PIN you can use:

      $sms->insertPin(null); or $sms->insertPin(”);

      as I explain in a previous comment. If not you must be sure that you are using the right PIN number. Extract the SIM card and try to use with phone.

      Anyway I’m not sure what you mean with PIN AUTH

  5. tnks for reply. erm. im tryin to use the php sms class. but, theres a part of code that gives a IN AUTHENTICATION. i get the PIN INCORRECT. althought the pin that i’ve configured its OK. the right one. can u help me erasing the part of PIN nUMBER authentication?
    please giv me your mobile phone number.
    tnks a lot.

    1. github repo modified, adding debug flag (check last commit). Now you can add an extra parameter called $debug (bool) to see the each output of the communication with the modem.

      As I can see that’s seems it’s not a problem within the auth part in the script. If the device has a pin number you need to send the pin in the script.

      It seems a promen in the serial port configuration, not with the pin. The script throws an exception the first time the script connect to the gsm device. I cannot affirm what the problem. I assume you’re using a linux box (remember windows is not supported) and using the serial interface (not the http interface). Is the serial port well configured (baudrate, parity, …)? Try to use minicom to speak with the gsm device first. It must work properly.

      Anyway you can change the script in your local copy to fit to your requirements if you want

  6. does this work on any network as long as we have the GSM modem device and the codes? what else are the requrements?

    1. I use this script with a GSM device connected to the a serial ethernet converter over a LAN. You can connect the GSM device to the server (without using the serlal converter), but I preffer using serial converter, because normally I’ve got problems with free serial port on servers and the longitude of the serial cable.

    1. Good question. All my devices are GSM devices. AFAIK 3g and gsm devices uses the same AT+ commands to send SMSs, so it must work with a 3g modem too.

    1. IT depends on the device. It it has a serial interface you can use the same technique, ¿Do you have more information about the RFID reader?

  7. Hello…
    Thanks for your script , really nice.

    One question here , can I skip the insert pin function?
    Because I set crontab will automatically refresh the script every selected minutes , but sometimes it will have PIN incorrect problem and stop execute.

    Thank you so much.

    1. I don’t understand your problem. I use this script in a crontab indeed. If you check the source code you will see that the first thing I check is if the PIN is OK. If not, I insert the PIN.
      If you skip this the pin your script will fails if you restart the modem.

      Anyway you can skip the insert of the pin without problems or even use it wtihout pin code (if you set up your device with no-pin, of course)

      1. Thanks for your reply.

        I set crontab to load the script every 10 minutes , for the 1st or 2nd 10 minutes it works very well , after that it will stop execute . I not sure what’s the problem so I try to refresh it myself using firefox , and sometimes it will show me PIN INCORRECT.

        PS:I have a script which can send long separate sms in PDU form,I wish to add this in your script but not really know how . Wonder is it possible to show you the script and have a small discussion?

        Thanks you so much.

  8. m using this code with GSM MODEM
    i can send email to any number
    but m unable to read messages from sim

    m using
    readInbox($mode=self::ALL)

    public function readInbox($mode=self::ALL)
    {

    $inbox = $return = array();
    if ($this->_pinOK) {
    $this->deviceOpen();
    $this->sendMessage(“AT+CMGF=1\r”);
    $out = $this->readPort();

    if ($out == ‘OK’) {$this->sendMessage(“AT+CMGL=\”{$mode}\”\r”);
    $inbox = $this->readPort(true);
    }

    i was trying to check
    print_r($inbox);

    it gives me output of

    Array
    (
    [0] =>
    [1] =>
    [2] =>
    [3] => OK
    )

    pleas help me . ma work is completely stuck .

  9. Try to read SMSs without the script. Use minicom (linux) or hyperterminal (Windows). Use the same commands:
    AT+CMGF=1
    AT+CMGL=”ALL”\r

  10. Hello.Can I know is it okay to set device every time when I need to send message?
    or just need to set for once?Will it cause any problem to modem if I send a lot sms and set device every time in my script? Thanks.

    1. It works fine, but if you are going to send big amount (a really big one) of SMSs you probably will need a dedicated server. Your server load will be increased too much. As far as I know we can use libevent extension with PHP but when I need to do this kind of things I prefer to use python or nowadays node.js

      1. Thanks for your reply.
        Yes I do have a dedicated server for sending sms , and I just simply use while loop to send messages.(about few thousands or even more through 12 ports.)To avoid each port from having too high traffic so I just set them to send few(about 6 messages) within a minute. But sometimes some of my modem’s ports will no longer working , it can’t detect SIM or even can detect but can’t send any sms , I’m wondering is it because sending too much sms causing the ports fried or modem quality problem? I even thought is because I set device too often causing the problem…

        I’m so sorry for this non-related topic here,I really can’t find anyone to answer me since no one really know GSM modem..

        Anyway still thanks again.

      2. My experience using serial ports is really bad. I had issues similar than yours. I also had problems finding servers with more than one serial port, usb2serial converters, … Because of that, now I always use ethernet converters. They are better to scale.

  11. hey..
    I need your help..maybe u can help me..
    I’m making an SMS application for Android which will send it’s location in the SMS content.. I mean the SMS message will just fill with the androids’ latitude & longitude that I got from the androids’ GPS..
    the SMS will received in a GSM modem in my laptop..
    on the other hand, I made my own map using google APIs V3 fill with some police station markers..
    I wanna show the SMS content (lat & long) on the map so the user will know the shortest path to the police station, but I don’t know how to do it..
    can u help me?
    I’m sorry for my poor English..

    1. I don’t understand your problem. If you want to send sms from android maybe you’ll need to use it’s own API (I’m not an android expert). Anyway, are you sure you need SMS? you can do it using simple http connections (cheaper). Fetch the GPS data from the android API and send as a rest webservice to your server (a simple web server)

      You can use my script at your server side to read SMSs

  12. Hi, Gonzalo Ayuso, thanks for your smart script. I tried to use the script on windows with my HTC HD mini mobile phone but when i run the script (testHttp.php) this error message appears—> “SOCKET ERROR”. I have noticed several times in your replies , that you didn’t test the script on windows but still do you have any idea why I am getting the error message?

    I plugged in my HTC HD mini phone to my USB port and then I run the testHttp.php from my localhost. I am a newbie to PHP so please kindly overlook my ignorance.

    Thanks in Advance 🙂

    1. If your GSM device has a usb you can use it without problems. See what port are you using. You can see the port easily:
      unplug the device
      tail -f /var/log/messages (or syslog path)
      plug the usb
      you will see the port in the log

      You also can use usb/serial converters

  13. Hi Gonzalo,

    Great Piece of work , I have a 16 port modem connected to Windows PC via USB Serial Converter. I have some questions regarding your script.
    1. Should I run the script on the same windows PC ?
    2. If I run the script from a network attached PC where do I mention the COM Ports
    3. I have a dedicated IP on the system which has the 16 port pool , how can I connect via PHP on another server ?

    Thanks for the help in advance

    1. I use the serial-ethernet converter to conect my serial devices to a server (located inside a data center). If you use this configuration you don’t need to connect the modem to a PC. You modem is now a network device. You don’t need to mention the COM port

    1. Yes. I still use this code. The Modem is the same than the moden I’m using (couple of years ago it wans named Wavecom, but now AFAIK Sierra bought Wavecom and the device has differnt name). I use also moxa converter, but your model isn’t a serial ethernet converter. It’s a Fiber- ethernet converter. Have a look to this one: http://www.moxa.com/product/NPort_5110.htm

  14. I want to use it on Windows So What kind of changes I have to make. I am running testhttp.php but its showing a message like “SOCKET ERROR”.

  15. Hi, I’m designing a website for blood donors in which i want to send sms from website to mobile. Please tell me the code and which server i need to run php. now I have wamp installed will it work on it? I have a trial gateway Nowsms i run that sing its port number localhost:8800 it shows its home page from where i can send msg to intended mobile number but i want to send it from a html page so plz give me all detail with code and where to store it and what changes in ip address,port etc i need to change in code plz i need it urgent. I have no idea about PHP so need little more explanation where to store and how to run on server and all plz

    1. If you are using a SMS gateway you need something different than this post. You need to build a http client according with the documentation of your gateway. You need to ensure that it allows you to automate sents via API or something like that. You don’t need PHP to do that. You can use the backend languaje of your website

  16. could you pls provide me a form using this code in php?? do i need an sms gateway?? do u have a video demo for this?? i am a student so i need a lot of comprehension about this.. thank you!!

    1. You can see the usage examples within the post. You don’t need a gateway. You need a real GSM modem (you can see the model of the modem that I use in the post too)

  17. Hey Gonzalo. First let me congratulate you for the help and the contribution that you are giving to people. I´m Sylvestre from Brazil. I´m now in the PHP world but I´m really enjoying it. I want to use SMS for my project, and I need an help. First for receiving and sending sms, with your experience, what can you suggested between using a SMS GSM modem, or Use the mobile phone as a gateway? According to the volume of sms to be sent and received. It about to receive around 50 thousands SMS and sent around 100 thousands. Do you have any tutorial about each case where I can see the implemented code for the PHP? I will really appreciate your reply.

    1. If you don’t have enough budget you can use one old phone as modem (if it allows to use the modem in one way or another) but if you need to build more robust system I recommend to buy a modem.

      According with the amount of sms (I don’t know if you are speaking about per day/hour/month …)., you must realize that send one sms whiting a modem is not very fast (1 second or even more), so if you plan to send big amount of SMS maybe you need to think in a cluster of modems to send SMS in parallel. But maybe it’s better to speak with your sms provider. They usually have a API or service to send SMSs directly without using a modem. They also offer discounts per sms if you work big amount of messages.

  18. sir?? will this work in windows??? if yes, whats the first thing to do??? can i use a GSM modem made by huawei?? thanks again…

  19. Sorry as I told before the script doesn’t work in windows. The original class (in which serial interface is based on) yes, but I’m not windows user so I remove it (I cannot test it)

    By the other hand if the device has a serial interface and you can send AT+ commands it should work propertly.

    1. I don’t really know what USSD is (I Know This, Because Tyler Wikipedia Knows). BTW This library is a wrapper to send AT+ commads through a serial interface. If your USSD device has a serial interface (and one protocol similar than AT+) it should be possible to adapt it.

  20. Dear sir;
    Before opening any port or running PHP script. Is it necessary to connect USB to serial converter with laptop USB port?

    If yes then is it necessary to connect GSM MODEM at other side before running code?

    1. you need to be able to speak with the modem. If your modem is a serial device you need to connect to your serial port (modern laptops don’t have serial port). In this case you need a serial-usb converter. I’ve had bad experiences with serial-usb converters, because of that I preffer to use serial2ethernet converters (they also give me more flexibility). Modern modems has also USB interface

  21. Thanks Gonzalo but I’m having some trouble. I can read messages and delete messages on the modem fine but my modem isn’t sending SMS messages. The script seems to hang when I send a message, other times I do not get the +CMGS response back — just an OK. Any ideas?

    1. You need to use the proper tty in your installation. You can see what interface are you using inspecting the /var/log/messages (or /var/log/syslog in ubuntu) when you plug and unplug your device. Either way if you can read messages I suppose that you are using the correct tty.

      Is your device AT+ or OPEN AT+. Modern modems are OPEN AT, and the protocol is a bit different. I need to upgrade the library to support OPEN AT. The only difference that I faced is the way of sending messages in text mode: AT+CMGS=”[number]”\r[text]Control-Z is not the way. Now we need to use:

      AT+CMGS=”[number]”\n
      then the device sends the string “>” and when it’s sent we can send:
      [text]Control-Z

      I need to change a little bit the function sendSMS in class Sms (line 120)

      1. Hello Gonzalo,

        Firstly I would like to thank you for your entire blog and just a general thank you to open source developers like yourself for the time you devote to helping people.

        I found this blog linked from the original php serial class ramsey posted and have read this blog post through from top to bottom and it’s a coincidence that jalpa asked this question as I believe it is pretty much exactly what I will eventually need to do but seeing as you say it’s outside the scope of this post, could you please fire me a quick email as I would love to get your help and opinion on a few things related to this post.

        Thanks

  22. hello Gonzalo
    I want to add GSM modem with the web interface(php)…So how to implement this with your code.

  23. deviceSet(“COM2”);
    $serial->confBaudRate(9600);
    $serial->confCharacterLength(8);
    $serial->confParity(“none”);
    $serial->confStopBits(1);
    $serial->confFlowControl(“none”);
    $serial->deviceOpen();
    $serial->sendMessage(“AT”);
    $serial->sendMessage(“at+cmgf=1”);
    $serial->sendMessage(“AT+CMGS=09353283866”);
    $serial->sendMessage(“HI GLENN”);
    $serial->sendMessage(“\x1a”);

    echo “Message sent Daw2222!”;

    $serial->deviceClose();
    ?>

    im using this code and there is no error.. but then i can’t receive any message coming from the modem. please help. i’m using SIM900D
    thank you in advance. God Bless 😀

      1. As I said before I’m not a Windows user so I cannot help you with this issue (In fact the library doesn’t work with windows). You should use the original serial library (see the link above) or use a serial ethernet-converter

  24. my teacher leave me this given problem for me:
    to access my gsm port i need to use this minicom-o maya
    the ip is : 192.31.1.85
    the password is : compLit

    how can I change the serial and the port?
    $serialEternetConverterIP = ‘192.168.1.10’;
    $serialEternetConverterPort = 1113;
    $pin = 1234;

    we’re using linux

  25. Gonzalo, muy bueno el ejemplo! Te consulto, podrás ayudarme con un ejemplo para enviar con php via telnet los comandos AT para enviar un sms, tengo un gateway portech y estoy con un ejemplo que encontre en la red, pero no lo puedo hacer funcionar.
    Muchas gracias por anticipado!

    Saludos cordiales,

  26. Hello Gonzalo.
    Thank you for this wonderful code.
    I try to use it on my mac with a Huawei USB modem, but I’m stuck and I don’t know why. I have first added some code to serial.php to make it work on MacOS X :

    function __construct()
    {

    elseif(substr($sysname, 0, 6) === “Darwin”)
    {
    $this->_os = “osx”;
    register_shutdown_function(array($this, “deviceClose”));
    }

    }

    function deviceSet($device)
    {

    elseif($this->_os === “osx”)
    {
    if($this->_exec(“stty -F ” . $device) === 0)
    {
    $this->_device = $device;
    $this->_dState = SERIAL_DEVICE_SET;
    return true;
    }
    }

    }

    Then in testSerial.php, I use these parameters :
    $serial = new Sms_Serial;
    $serial->deviceSet(“/dev/tty.HUAWEIMobile-Modem”);
    $serial->confBaudRate(115200);
    $serial->confParity(‘none’);
    $serial->confCharacterLength(8);

    “/dev/tty.HUAWEIMobile-Modem” comes from the tests I made in MacOS Terminal :
    screen /dev/tty.HUAWEIMobile-Modem
    That gave me access to AT commands to send and receive SMS in the Terminal. Si it should work in my PHP script, no ?
    Any idea ? May be it could help some other Mac users…

    Thank you in advance

  27. Hello again.

    I have made a little change in the deviceSet function; I changed :
    if($this->_exec(“stty -F ” . $device) === 0)
    for
    if($this->_exec(“stty -f ” . $device) === 0)

    Know, when I execute the script, it never reaches its end.
    And after that, I have a look to the running process in the Terminal and I discover a “screen” command which state is “stuck”. I try to kill it but it doesn’t work :
    sudo kill -9

    Strange no ?

  28. Ok, I looked back to the Mac Terminal and got informations there :
    First, Mac Terminal doesn’t recognize -F option for stty.
    Second, when I run stty -f… in Mac Terminal, it does as if a port is open and wait for something else. As don’t know what, I am just able to close it which Ctrl-z.
    Obviously, that’s why my PHP script never ends when it runs $this->_exec(“stty -f ” . $device).
    So what shall I do to make it work ?

    Thank you in advance

  29. I continue my investigation. I reboot my Mac and try to run again stty -f in Terminal. And then the result is different, displaying infos about the modem plugged on this port. So it looks like the stty -f command works fine on Mac, but when I run the PHP script, there’s something wrong happening that make it not work anymore. Probably, as the script never ends, the port is open, but never closed, so when I try to access it again in Terminal, it is already open. But what prevents the script to reach its end ?

  30. Ok, I have found the PHP command that makes the script never ends :
    $this->_dHandle = fopen($this->_device, $mode);
    I tried to replace fopen with file_get_contents. Then the script reach its end, but the file is not open anymore.
    Could anyone help me ?
    Thank you in advance

  31. Hello Gonzalo,
    I’m trying to find an USB Surf stick or a piece of software which is creating virtual com ports so I can use AT commands to send SMS. But the USB sticks Huawei E3131 and the D-Link DWM157 do not create the ports when I stick it in a USB Port.
    The D-Link surf stick creates the ports only when I start the D-Link Software. But then the port numbers changes often (COM21, COM11, COM..) after restarting the System. Is there a way to create the com ports manually, so the numbers are fixed ?
    I will send the AT commands from within my visual Basic application to the com port.
    Many thanks for your help.
    Peter

    1. It looks like you are using windows. I don’t have experience with it. Another solution is attach the stick to a usb/ethernet converter (or a compatible router) instead to the pc and send AT commands with sockets.

  32. Hiho gonzalo, Great code. Maybe you can help me.

    Im having pin error, so i’ve try many of pins and insertPin(null)

    none of them sold the pin problem, so i’ve tested the reply from insertPinf function

    in this point

    $this->sendMessage(“AT+CPIN?\r”);
    $out = $this->readPort();
    $this->deviceClose();

    the out comes empty

    so i did add an new case

    default :
    echo “passing by default “;
    $this->_pinOK = true;
    break;

    it pass by default and finaly returns sent Error

    on the original code you use “/dev/ttyS0” my serial port is on /dev/ttyACM0 so i did try both. And both i got same error,

    do you have any idea about what can i do to solve it ?

    1. If you need to handle 16 modems I recommend to use one process per modem (or maybe one gearman server with one worker attached 16 times). If you use a single thread to handle all modems it’ll be definitely very slow (modems takes time to send SMSs)

      1. Okay i think i solved problem, but i can’t read inbox.

        Funkction:
        public function readInbox($mode=self::ALL)
        {
        $inbox = $return = array();
        if ($this->_pinOK) {
        $this->deviceOpen();
        $this->sendMessage(“AT+CMGF=1\r”);
        $out = $this->readPort();
        if ($out == ‘OK’) {
        $this->sendMessage(“AT+CMGL=\”{$mode}\”\r”);
        $inbox = $this->readPort(true);
        }
        $this->deviceClose();
        if (count($inbox) > 2) {
        array_pop($inbox);
        //array_pop($inbox);
        $arr = explode(“+CMGL:”, implode(“\n”, $inbox));

        for ($i = 1; $i $id, ‘tlfn’ => $fromTlfn, ‘msg’ => $txt, ‘date’ => $date, ‘hour’ => $hour);
        }
        }
        return $return;
        } else {
        throw new Exception(“Please insert the PIN”, self::EXCEPTION_NO_PIN);
        }
        }

        Not working for me, i give only this (i’m enabped debug):
        +CPIN: READY OK Array

        But i know inbox are more then one SMS.

  33. Hey Bro can you guide me what should I do? I want to make a PHP system on windows which can read SMS and send SMS back using GSM device… For this pouropse what should I do? Do I need any Database to maintain record etc?

  34. hi, much thanks for the scripts
    sorry for my bad english
    i open this script(testSerial.php) on browser and i found error :
    it says “PIN Incorrect”
    how can i use this script to work, is there any setting that i must do before?

  35. Hi thank you for this tutorial but what if I want to read every income message from USB MODEM with it sim card in PHP Functions and then check for relevant things and SEND it to the DATABASE by QUERYING them.

  36. hi sir gonzalo, I am actually interested with your work. The Send/Read sms, cause I am also currently working on that thing, but I am using VB.NET sir.

    By that, I have a question sir. How can I delete messages from the gsm device. cause I have tried a lot, and I can’t get it. no error, but the message is still in the device.

    I am using HUAWEI GSM MODEM, certainly with GLOBE TATTOO Broadband sim.

    I am looking forward for your answer sir. Thanks

  37. hi sir gonzalo, I am actually interested with your work. The Send/Read sms, cause I am also currently working on that thing, but I am using VB.NET sir.

    By that, I have a question sir.
    How can I delete messages from the gsm device? Cause I have tried a lot, and I can’t get it. No error, but the message is still in the device.

    I am using HUAWEI GSM MODEM, certainly with GLOBE TATTOO Broadband sim.

    I am looking forward for your answer sir. Thanks in advance.

  38. HY SIR,,,
    i am using gsm modem for sending and receiving sms on windows ,,,,can u plz send me the code for this in php
    i am window 7 user
    my gsm modem is SIM900D

  39. Hi Gonzalo Ayuso,
    I hope you are well.
    I am from kenya and i need your help.
    I have a php,mysql,apache web application running on a local computer using wampserver.
    I wish to send an sms to a two mobile numbers typed on two html form textboxes.
    How can i achieve this
    Kindly help.
    I have seen your sms sending articles done in object php and some areas where not clear.
    Could you please help.
    How can include your php files to my application and call them when i need to send the sms.
    can i use a mobile phone with usb cable or i have to use a modem.
    Kindly help
    Thanks
    David

  40. this post is pretty informative. I have one problem implementing this code in C#. I am using GSM USB dongle to send the SMS using AT commands. We are using USB and internally connecting to the ports that it is being used. we are able to send and receive messages with the dongles which are using com ports. however modern USB dongles are not using com ports and we are not able to send and receive messages… could you please guide us a way to connect to those dongles also…

    1. Nowadays I don’t use com ports (even with usb dongle). It’s hard to find hosts with serial ports (modern mobile modems have usb interface). I’m using serial to ethernet adapters. It’s more easy and I don’t need to have the modem close to the host. I cannot help you with usb interface but afaik usb dongle is transparent to to the user. You can use the usb port in the same way than a serial one

  41. Hi Gonzalo,

    Note: I want to create system.

    I have a database in which store some data related to student and i already create hope page in which user put your roll number and and your cell phone number and i want our system get student phone number and and send the details on cell phone.

  42. Hey,
    I have a LAN GSM Modem connected with Lan Cabel on my router and now I want to send through my PC to the IP Adress of the GSM modem the command, that the modem has to send a SMS to my mobil phone number.

    Is the file testHttp.php for me the right one ?

  43. Hello, I need a little help, please. I usually have a USB dongle from vodafone. I install it and it creates a virtual com which I can use with my programs. Using windows 10 it does not happen anymore. Everything works but COM ports are missing. So I’m asking you, do you know how can I have my COM ports back? or, what should I buy exactly to use my usb dongle as you suggested? thank you!

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.