Getting out of PHP jail by crawling out a pipe

It’s not uncommon to find hosting that cripples PHP by disabling the very handy exec(), passthru() and system() functions (which let you have the underlying operating system execute a program, doing different things with the output). If you use Perl, you’ll be able use system(), or backticks or qx// to your heart’s delight, but because PHP makes it easy to disable the common functions that let you get to the OS, people do.

Luckily, they quite often miss a little something: popen() is a lovely function that opens a pipe to a process created by forking the command you pass as an argument. (That explanation may well be why they miss it, or decide that anyone using it knows enough not to destroy the world.)

You get back a file pointer, just like if you had used fopen(), on which you either fread() or fwrite() (or whatever your favorite way of dealing with files may be). You don’t get both: it’s either read or write, but for my purposes writing’s usually something for the command line, and reading’s all I need.

So, what can you do with it? Say you’ve installed the Feed Validator, and you want to use the included to check a feed from PHP:

$feed = '';
$handle = 
    popen("python ~/rssvalidator/src/ $feed 2>&1", 'r');
$read = fread($handle, 2096);
// if (!strstr($read,'No errors or warnings') die("Oopsie!");
echo $read;

Or, suppose you wonder how you are doing at delivering 304 Not Modified for your RSS, but don’t feel like writing a whole log file parser in PHP? (I stole this from a comment by Abe Fettig: makes me wish I hadn’t fallen asleep every day in CLI Class)

$command = 'grep "GET .*xml" ~/logs/ ' . 
    '| cut -d ' ' -f 9 | sort | uniq -c';
$handle = popen($command, 'r');
echo fread($handle, 2096);


No comments yet.

Name (required)
E-mail (required - never shown publicly)
Your Comment (smaller size | larger size)
You may use <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <del datetime="" cite=""> <dd> <dl> <dt> <em> <i> <ins datetime="" cite=""> <kbd> <li> <ol> <p> <pre> <q cite=""> <samp> <strong> <sub> <sup> <ul> in your comment.