Serial comm with PHP on Windows

Every solution above is either inefficient or too much work.

You can just use the PHP-DIO library (dio_fcntl, dio_open, dio_read, dio_write, dio_seek, ...). It's also in the PHP manual's entry for DIO:

This PECL package isn't available by default. To get it for Windows if you have PHP 5.2.x greater than 5.2.6, you can download it as part of a ZIP:

  • Thread-safe (for Apache)

  • Non-thread-safe (for IIS)

Both of these links were found in http://www.deveblog.com/index.php/download-pecl-extensions-for-windows/

Here is the build from Linux, just get it and do the phpize/configure/make/make install thing.

I don't know whether it should be used in an Apache session, but go for it.


You need to set up the com port using a DOS-like command.

For example, the following line executes the command through php:

$output = `mode COM1: BAUD=115200 PARITY=N data=8 stop=1 XON=off TO=on`;

To display the results you can use:

echo "$output"; 

Create the resource id:

$fp = fopen('COM1', 'r+');

if (!$fp)
{
      echo "Port not accessible";
}
else
{
     echo "Port COM1 opened successfully";
}

Write to port:

$writtenBytes = fputs($fp, "Hello");

echo"Bytes written to port: $writtenBytes";

Read from port:

$buffer = fgets($fp);

echo "Read from buffer: $buffer";

Maybe someone can help me with the fgets problem. It stacks there for exactly one minute if TO=on, or stacks there forever if TO=off. It seems to be a "MODE COM" option so maybe a DOS expert can help.

Perhaps instead of fgets, one should use fgetc, since fgets capture through to the newline, while fgetc captures a single character. If a new line isn't encountered, it may block until there is one or until the buffer is flushed. The one minute delay may be windows flushing its buffer on an interval.


The easiest way to tackle this would be to write a program in another language (such as C++) and then execute it from your php script with system(). Doing Comm I/O in C++ is trivial.

This assumes you have enough access to the server to configure it to allow the executable to be run by php, etc.