PHP and named pipes
Wednesday, August 29, 2007 4:53:17 AM
There are a few things you could do to achieve this:
- Create a file and poll it with your server for new data
- Use a database and poll it from your server for new rows
- Use a named pipe
As you can see from the list, all other options except named pipes require you to perform polling. With files you'd need to open and reread the file and with the database you'd need to perform queries to check it for new rows. With a named pipe, the application can just open it and wait for data.
Creating a named pipe
For starters, you will need to create the pipe. This can be done from the shell with the command mkfifo pipename which will create a pipe called pipename.
To try reading the pipe, you can use cat pipename which will read the contents of the pipe, but will wait if there is nothing in it. To write something to the pipe, you can use echo "some stuff" > pipename
So basically the pipe works almost like a file. Perhaps you can guess how we can use the pipe from PHP or the server already...
Creating a simple server
Let's create a simple Python script that will read our pipe. This script will even create the pipe for us, so we won't need to do anything else than just run it.
import os
# the name of the pipe
pipeName = 'testpipe'
# we will get an error if the pipe exists
# when creating a new one, so try removing it first
try:
os.unlink(pipeName)
except:
pass
# create the pipe and open it for reading
os.mkfifo(pipeName)
pipe = open(pipeName,'r')
# read forever and print anything written to the pipe
while True:
data = pipe.readline()
if data != '':
print repr(data)
You could use this to read your pipe. You can run this script with python nameoffile.py
Now, let's continue to...
Writing to a pipe with PHP
Now we just need a PHP script that writes to the pipe. Can you guess how it's done? Yep, fopen and fwrite.
<?php
//Open pipe and write some text to it.
//Mode must be r+ or fopen will get stuck.
$pipe = fopen('testpipe','r+');
fwrite($pipe,'this is some text');
fclose($pipe);
?>
Save that to some file, open it in your browser and look at your server... simple huh?
Some other examples of using pipes usually tell you to use proc_open or some other more complex method with PHP and using cat with Python, but this is probably the easiest way to do it.







Anonymous # Monday, June 29, 2009 12:50:00 PM
Andrey Anavarrxsportmeds # Thursday, December 3, 2009 10:01:47 PM
I used php a long time, but now I know what python)
Anonymous # Sunday, September 12, 2010 12:08:02 PM
Anonymous # Monday, April 18, 2011 1:57:53 AM