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)

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:



$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:


$pin = 1234;

try {
    $serial = new Sms_Serial;

    $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";
        case Sms::EXCEPTION_PIN_ERROR:
            echo "PIN Incorrect\n";
            echo "Service Not implemented\n";
            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:


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

    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";
        case Sms::EXCEPTION_PIN_ERROR:
            echo "PIN Incorrect\n";
            echo "Service Not implemented\n";
            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

About Gonzalo Ayuso

Web Architect. PHP, Python, Node, Angular, ionic, PostgreSQL, Linux, ... Always learning.

Posted on March 21, 2011, in php, Technology and tagged , , . Bookmark the permalink. 125 Comments.

  1. hi, i don’t checked it but if it workin that is very good idea!!:) thanks for sharing

    • 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).

      • Hi GOnzalo? What if i have windows, not linux, what must i write instead “/dev/ttyS0” and i have usb stick not serial device? thanks…pls write me back…

      • 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

  2. When I found a little time I’ll testing it (and let you know), I use linux too:) thanks again;)

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

    Thank you very much.

    • I normally use this one (modem) and converters from different vendors. Normally

      • 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

  4. Thanks for the source code!
    I was looking for something like this.
    I just want to get home to test it.
    Thanks again!

  5. Gonzalo Ayuso

    Great! I hope it will be useful

  6. 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!

    • Gonzalo Ayuso

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

  7. can u tell me how to implement this on windows environment?

    • Gonzalo Ayuso

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

      • Rajendra Pondel

        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.

        Rajendra Pondel.

    • Gonzalo Ayuso

      “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)

  8. 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!


    Jaan Colman

    • 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 …


      • Gonzalo Ayuso

        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) 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

  9. 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!


    Jaan Colman

  10. hi, My Sim does not have PIN, if i m putting $PIN=””; it says PIN Incorrect, what should i do ??

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

  11. In windows the http.php is not working please help me…

    I have downloaded a new http.php file from

    Coming Soon Live

    This file shows pin invalid.

  12. “Service Not implemented”
    what does it mean?



  13. PIN INCORRECT. how can i deactivate PIN AUTH? please help me Gonzalo! really i need heeelp!!!

    • 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

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

    • 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

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

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

  16. can you use 3G modem with the same code?

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

  17. Hi Can you teach me, how do I connect RFID with PHP. In order to read data from RFID Reader in realtime

    • 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?

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

    • 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)

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

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

    m using

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

    $inbox = $return = array();
    if ($this->_pinOK) {
    $out = $this->readPort();

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

    i was trying to check

    it gives me output of

    [0] =>
    [1] =>
    [2] =>
    [3] => OK

    pleas help me . ma work is completely stuck .

  20. Try to read SMSs without the script. Use minicom (linux) or hyperterminal (Windows). Use the same commands:

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

    • 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

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

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

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

    • 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

  23. 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 🙂

  24. I am a ubuntu user .
    I want to use this script by usb port.
    How can i do that.

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

    • 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

  26. Hi Gonzalo,

    Is this code still working on your system ? Also want to know if you are still using the same 2 devices as below as we are also planning to implement sms system 🙂


    • 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:

  27. 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”.

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

    • 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

  29. 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!!

    • 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)

  30. Sylvestre Somo

    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.

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

  31. 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…

  32. hello sir… where are the html tags or the design of the form?? how is it look alike

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

  34. sir, may i ask a question… how to run my application in a web browser/php???
    thanks a lot

  35. Hi

    Great post. Thanks for taking the time to post this.
    I would like to discuss a USSD command project i have if you are interested. Please leave me email me on


  36. Sorry if this out of topic, Can this script be modified to be able to invoke USSD command by GSM modem? Please help.

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

  37. 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?

    • 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

  38. 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?

  39. Would using ttyHS0/HS1 instead of ttyS0/S1 be a cause? I can’t use S0 to with my modem

    • 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:

      then the device sends the string “>” and when it’s sent we can send:

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

  40. Thanks Gonzalo, Will give it a practical try in the next week 🙂
    Favorited on github.

  41. i want to store sms in to mysql database then what to do for it?

    • You can do it but it’s out of the scope or this post. Read the sms and save into database

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


  42. but how i can save it?

  43. Himanshi Sharma

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

  44. it is really helpful

  45. deviceSet(“COM2”);
    $serial->sendMessage(“HI GLENN”);

    echo “Message sent Daw2222!”;


    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 😀

    • And also im using Windows.. Thank you!

      • 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

  46. What hardware do you use/propose to connect to an usb (male) connector over http protocol as proposed in the sms_http class?

  47. Probably you can find a usb-eth converter (I never used), Also you can find a usb+serial adapter.

  48. 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 :
    the password is : compLit

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

    we’re using linux

  49. 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,

  50. 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;

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

  51. Hello again.

    I have made a little change in the deviceSet function; I changed :
    if($this->_exec(“stty -F ” . $device) === 0)
    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 ?

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

  53. 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 ?

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

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

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

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

    $out = $this->readPort();

    the out comes empty

    so i did add an new case

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

    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 ?

  57. Found It, permission added wwwrun to dialout group and solve. working xD

  58. Hi, i try test this script with 16 ports modem, but speed is wery low

    • 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)

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

        public function readInbox($mode=self::ALL)
        $inbox = $return = array();
        if ($this->_pinOK) {
        $out = $this->readPort();
        if ($out == ‘OK’) {
        $inbox = $this->readPort(true);
        if (count($inbox) > 2) {
        $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.

  59. 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?

  60. 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?

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

  62. Cherwen Mara Molina

    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

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

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

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

  66. 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…

    • 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

  67. Hi, if anyone is interested in sending SMS through PORTECH MV-37XX, check this out:

  68. Great post, most informative, didn’t realise devops were into this.

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

  70. Hi Gonzalo it is working in unbunto os?

  71. 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 ?

  72. 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 Reply to rysio Cancel reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

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

%d bloggers like this: