Script: Preprocess PHP

PHP doesn’t come with conditional compiliation or any preprocessor tools, but using a generic preprocessor can make life much easier. Conditional compilation is just that — blocks of code can be set to only compile and run if a certain condition is met. Many compiled programming langauges support this, such as C/C++, Pascal, and others.

First, install preprocess (python required): $ apt-get install preprocess.

Next, we need a test script:

<?php echo "test1"; ?>
#define DEBUG 1
# #if (DEBUG == 1) 
echo "test2 DEBUG"; 
# #endif
<?php echo "test3"; 

Finally, we need a wrapper to preprocess input files and then execute them.


define('BIN_PP',      '/usr/bin/preprocess');
define('DEBUG',       false);

$input = $argv[1];
$ppargs = "";
if (DEBUG) {
  $ppargs = " -DDEBUG=1";
} else {
  $ppargs = " -DDEBUG=0";

$cmd = BIN_PP . "$ppargs '$input' ";

$data = shell_exec($cmd);

$hash = sha1($input);
$tmpfn = "tmp_${hash}_$input";

file_put_contents($tmpfn, $data);
passthru("/usr/bin/php -f $tmpfn");

Usage: $ preprocess-php test.php
The preprocess-php script assumes that the input file is a php file.

TODO: allow multiple files on command line
TODO: only preprocess and execute .php files

Permanent link to this article: http://permafrostcodingstudio.com/articles/script-preprocess-php/

Leave a Reply

Your email address will not be published. Required fields are marked *