Main Content

Stand alone PHP programs

Archive - Originally posted on "The Horse's Mouth" - 2005-10-18 02:26:23 - Graham Ellis

It always seems a shame when people develop a lot of code in PHP then want to use it standalone ... so they rewrite it in some other language or wrap it in a web page.

PHP is an excellent stand alone language; it wasn't designed for that use, but it does a mighty fine job if you've already got files full of functions that you want to use away from as well as on the web. Here's a sampple stand alone PHP program:


#!/usr/bin/php -q

The world of Belgian dressing

<?php

$interact = fopen("php://stdin","r");
for ($k=1; $k<11; $k++) {
print "$k dollops of mayonnaise\n";
$line = fgets($interact,1024);
}

?>

and there's a chip in there somewhere


Two notes:

1. The -q command line option supresses headers so that you don't get a "content type" line

2. The special URL php://stdin allows you to open the keyboard for read, thus it allows you to write a truly interactive program.