Home > php, Programming > Writing flexible php cli scripts with environment variables

Writing flexible php cli scripts with environment variables

For large projects it’s better to put configurations in a settings.php file and use require 'settings.php' in the main php file, but when it’s time to write some small script but also want some flexibility, using (shell) environment variables is a better choice.
cat main.php

<?php
        $d=getenv('debug');
        $debug=$d!=''?(int)$d:1;        // default debug mode is 1
        $p=getenv('preview');
        $preview=$p!=''?(int)$p:0;      // default preview mode is 0


        if(count($argv)<2) {
                die("Usage: [debug=0|1] [preview=0|1] {$argv[0]} arg1 arg2 ...\n");
        }
        echo "program starts with preview=$preview, debug=$debug\n";
        var_dump( array_slice($argv, 1) );

Different mode combinations can be achieved through, for example,

$ php main.php aa
program starts with preview=0, debug=1
array(1) {
[0]=>
string(2) "aa"
}

$ preview=1 php main.php aa bb
program starts with preview=1, debug=1
array(2) {
[0]=>
string(2) "aa"
[1]=>
string(2) "bb"
}

$ preview=1 debug=1 php main.php aa bb
program starts with preview=1, debug=1
array(2) {
[0]=>
string(2) "aa"
[1]=>
string(2) "bb"
}

$ preview=0 debug=0 php main.ph aa bb
program starts with preview=0, debug=0
array(2) {
[0]=>
string(2) "aa"
[1]=>
string(2) "bb"
}

$ export preview=1
$ php main.php aa bb cc
program starts with preview=1, debug=1
array(3) {
[0]=>
string(2) "aa"
[1]=>
string(2) "bb"
[2]=>
string(2) "cc"
}

$ php main.php
Usage: [debug=0|1] [preview=0|1] main.php arg1 arg2 ...

Advertisements
Categories: php, Programming
  1. December 26, 2011 at 5:40 pm

    Nice and great post this is very useful for us keep blogging. and thanks for share information with us.
    php string variables

  2. June 12, 2012 at 7:53 pm

    Awesome! Can’t tell you how helpful this was, been hitting a wall trying to make my crons code environment independent. This works nicely!

  3. ricoch3n
    June 14, 2012 at 1:52 am

    Glad to hear that this technique works for you. Indeed this is the best way to get away with messing around with the php scripts’ arguments (haven’t found a decent PHP command line parsing library yet, using getopt in PHP is never a pleasant experience, that’s why I turned to environmental variables for answer).

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: