Sunday, 29 July 2012 11:19

Control Serial via PHP

Written by
COM Port status COM Port status
It is simple to control serial via PHP.

exec("mode com4: BAUD=9600 PARITY=n DATA=8 STOP=1 to=off dtr=off rts=off");
$fp =fopen("com4", "w");
//$fp = fopen('/dev/ttyUSB0','r+'); //use this for Linux
fwrite($fp, "string to send"); //write string to serial

The first function exec is similar to the DOS command, use to change the port settings.
You can run mode from Ms DOS command prompt. For example:
C:\> mode com4:/status
The above DOS command display the status of the COM port. 

Syntax of mode (display a list of mode commands & options)
C:\> mode/?


Open COM4 in write mode (for Microsoft Windows only)

$fp =fopen("com4", "w");

or your can use  $fp =fopen("com4", "r+"); for read & write


Open USB serial port for read and write (for Linux)

$fp =fopen('/dev/ttyUSB0',r+');


Open first serial port in read & write (for Linux)

$fp = fopen('/dev/ttyS0','r+');


To terminate string with Carriage Return

fwrite($fp, "string to send\r");


To terminate string with New Line & Carriage Return

fwrite($fp, "string to send\n\r");


 Close the serial port




Additional Information about PHP Serial
There are many people using php_serial.class. Unfortunately it is not working in my computer. Please let me know if some one can make the following code work.

$serial = new phpSerial();
$serial->confBaudRate(9600); //Baud rate: 9600
$serial->confParity("none"); //Parity (this is the "N" in "8-N-1")
$serial->confCharacterLength(8); //Character length
$serial->confStopBits(1); //Stop bits (this is the "1" in "8-N-1")
$serial->sendMessage("string to send");

It is not important to me no matter the php_serial.class is working or not. I'm happy with the  $fp =fopen("com4", "w"); command since I do not need to include additional library file to my php source code.
Read 78976 times Last modified on Sunday, 12 June 2016 10:33
More in this category: HTML Onclick Button Image »


  • Comment Link Nikolayadomo Tuesday, 13 August 2019 19:01 posted by Nikolayadomo

    Наша компания оказывает услуги по ремонту и отделке квартир , офисов, загородных домов и производственных помещений любого уровня и любой сложности. Наши специалисты имеют высокую квалификацию и огромный опыт (более 10 лет) по производству качественного ремонта жилых и производственных помещений.

  • Comment Link AlektorovGJ Saturday, 27 July 2019 13:58 posted by AlektorovGJ

    Доброе утро.
    автоматизация технологических процессов, ремонт промышленной электроники, ремонт частотных преобразователей, ремонт устройств плавного пуска, ремонт силовой электроники, модернизация промышленного оборудования, наладка промышленной автоматики:
    FR-V240E-2.2K, SMC930200, FR-V220E-3.7K, CIMR-E7C40111, E1-P7002 100H, M200-06400420A, CIMR-XCBC40P4, M800-03400062A, FRN5.5VG7, ATV61EXS5C16N4, FR-A820-00490, E3-8100K-P5H, WJ200-001LF, CIMRG7C20151B, CIMR-F7Z40181, CIMR-F7Z41321B, E1-9011 150H, ATV61HD37N4Z, ATV12H018F1, ATV21HD22N4, CIMRG7C40750B, FR-A220-3.7K-UL, CIMR-F7C20181, FR-A241E-5.5K-UL, ATV71LD33N4Z, CIMR-F7Z20750, ATV71HU55N4, CIMR-E7C42200, FR-F740-08660, SJ300-185HFU, E1-9011 400H, EMX3-, SJ700-750HFUF2, CIMR-VCBA0003HAA, TMVRXE12-750-2300-12, FR-D720S-070, VFD055B43A, ATV71WD75N4A24, ATV61HD15Y, ATV71HD55Y, CIMR-G7A40370, CFW110242T4SZ, CIMR-E7Z45P51B, CIMRJ7AZ40P40, ATV61EXC5D90N4H, CIMR-F7C47P51, CIMR-V7AZ25P51, ATV61EXC2C63N, WJ200-001SF, ATS01N212LU, M400-074001000A, M400-01100024A, C104040, VLT 2800, IMS20585-V5-C24-F1-E0, PA7300-2060-N1, SMC920500-P, ATV312H075N4, FR-F520-3.7K, M800-09402000A, L200-004HFU, GP104010-4M, ATV312H037N4B, CIMR-V7SC20P27, M400-02400032A, CIMR-E7C20220, ATS22C41S6U, EI-7011-075H, CFW700E142T2NBN1C3, M400-05400300A, ATV71LD15N4Z, CIMR-G7C41100B, CIMR-F7Z43P71, SMC930400, FR-V240E-5.5K, FR-V520-22K, ATSU01N212LT, PA7300-4350-N1, M600-05400270A, ATV71EXC5C40N4, M600-03400025A, ATV61HU55N4Z, FR-A540L-530K, CFW100026SAPLZ, FR-Z220-3.7K-UL, IMS20047-V5-C24-F1-E4, CIMRF7Z41321B, CIMR MR5N 2045, EQ7-2040-C, CIMRG7C43000B, FR-D720-238, CIMRE7Z41101A, CIMR M5N 2030, CIMR-E7Z40750B, CIMRE7Z40301A, ATV32HU75N4, IMS20041-V5-C24-F1-E4, CIMR MTII 11, L300P-370LFU2, ATV71HU30N4383, и др.

    Prom Electric

  • Comment Link Lane Saturday, 01 June 2019 17:38 posted by Lane

    Представляем Вам нашу нашу коллекцию порно фотографий на сайте -
    урл . Смотри как стройные красавицы модельной внешности позируют перед камерой демонстрируя
    свои "прелести". Только самые страстные девушки готовые на все.
    Кстати, у нас ты найдешь не только гламурыне потрно
    фотки, но и необычные фото, так сказать на любителя, с разныеми фетишами и фистингом.
    Все фото архивы разбиты по категориям, выбирай понравишуюся и смотри совершенно

  • Comment Link admin Thursday, 15 June 2017 13:15 posted by admin

    Seems like the baud does not match

  • Comment Link Edward Eborgu Monday, 12 June 2017 17:49 posted by Edward Eborgu

    I wrote my code this way to send price to a display pole

    function sendTodisplayPole($com, $baud, $msg)

    $com= "COM1";
    exec("mode $com: BAUD=9600 PARITY=n DATA=8 STOP=1 xon=off");
    $fp=fopen($com, 'w');
    fwrite($fp, "total:78578");


    it worked but the display pole was showing unrecognized characters please help to know how to let this show the exact character im sending to the display pole

  • Comment Link Edward Eborgu Monday, 12 June 2017 17:46 posted by Edward Eborgu

    Hello i wrote my code this was

    function sendTodisplayPole($com, $baud, $msg)

    $com= "COM1";
    exec("mode $com: BAUD=9600 PARITY=n DATA=8 STOP=1 xon=off");
    $fp=fopen($com, 'w');
    fwrite($fp, "total:78578");


  • Comment Link Johnny Churne Tuesday, 07 February 2017 20:40 posted by Johnny Churne

    Thanks for a great article. I want to ask it is possible to send byte as hex from php to serial port?

  • Comment Link admin Tuesday, 07 June 2016 15:54 posted by admin

    Can you describe in more detail?

  • Comment Link Mehedi Hasan Polin Tuesday, 07 June 2016 15:03 posted by Mehedi Hasan Polin

    Hi i am from bangladesh. i try to develop bridge scale software with Apache/php

    i want to read data from com1 port to pc. please help

  • Comment Link admin Friday, 22 January 2016 18:47 posted by admin

    Have you tried on other computer?
    I'm using WAMP & EasyPHP without any problem.

  • Comment Link Elza Friday, 22 January 2016 03:38 posted by Elza

    Hello, I want to read data from Arduino, windows 7, 32 bit, Port COM4. I have the following code:
    PHP Code

    And I have the problem: fopen(COM4): failed to open stream: Permission denied in C:\xampp\htdocs\project\index.php on line 3

    Does anyone knows what's the solution?

    Thanks in advance..

  • Comment Link Admin Wednesday, 15 May 2013 19:56 posted by Admin

    Please refer this article in order to read & write to serial port

  • Comment Link smching Wednesday, 15 May 2013 19:47 posted by smching

    You can check your com port from device manager too.
    Sometime you have to send string terminate with new line or carriage return depend on your Arduino sketch.

    fwrite($fp, "string to send\n\r");

  • Comment Link chethan Saturday, 11 May 2013 23:46 posted by chethan

    i tried the program along with arduino .
    the problem that i am facing is that , after the php code is made to run in wamp ,a new file by the name com20( i have connected the arduino to com20)is being created in the wamp server directory and is nothing is being transmitted to board .
    can anyone please help me .

  • Comment Link Subhendu Saturday, 11 May 2013 10:54 posted by Subhendu

    I can write on the serial port using fwrite($fp,"0");
    Can you please provide me with a simple example on how to read from serial port.
    I am using Windows 7
    I want to display sensor data on my webpage.

  • Comment Link Subhendu Sinha Chaudhuri Friday, 10 May 2013 22:09 posted by Subhendu Sinha Chaudhuri

    I had my arduino attached in COM19 in my Windows 7 64bit. Using ur example I was trying to on the LED on pin 13. But nothing was happening. But the serial monitor of the arduino was showing the result on sending strings.
    In fact the c:\>mode com19:/status was telling COM19 is unavailable.
    Can u please help me
    I have also failed with php_serial.class in Windows after trying for 4 days.

  • Comment Link Admin Sunday, 21 April 2013 13:38 posted by Admin

    Any error message?

    What is the serial settings of your phone?

    Above examples only shows you how to sending messages to serial port, however your phone should running some kind of software to listen the serial port in order to process the incoming messages.

  • Comment Link okan Saturday, 20 April 2013 23:25 posted by okan

    i connect my cell phone(nokia 6300). i checked it is in com4. but in php i cannot connect com4 can you help me.

Leave a comment

Back to Top