Saturday, February 6, 2010

Using PHP from the command line

This guide is intended for PHP programmers. I found a number of Linux users asked why don't you do it in Linux shell?
Well, there are many possible answers:
  • Not many people familiar with Linux shell scripting
  • Don't want to learn another language
  • PHP have a lot of libraries
  • Who knows?
Requirements:
  • Unix/Linux like Operating System.
  • You must have php-cli.
This is how you install php-cli:
  • Ubuntu: apt-get install php5-cli
  • Centos: yum install php-cli
  • FreeBSD assuming that you have ports tree installed:
    # cd /usr/ports/lang/php5-cli
    # make config
    # make install
There are two ways you can run the PHP scripts:
  1. At command line: php your_scripts.php $arg1 $arg2 ...
  2. At the very first line of your php scripts insert this line if you are using Ubuntu, no space:
    #!/usr/bin/php5
    <?php
    If you are using other OS, replace /usr/bin/php5 with your PHP executable file. Execute your script:
    ./path/to/your_scripts.php $arg1 $arg2 ...
Let's go for a test drive.
Insert the following lines into a test file:
cat > test.php
Paste from command line (ctrl+shift+v):
#!/usr/bin/php5
<?php

foreach($argv as $key => $value){
    echo "\n" . $key . ": " . $value;
}
done with ctrl+c.

Now, you can execute the test.php file using any of the methods above.
  1. php test.php param1 param2
  2. ./test.php param1 param2
    Note: In order to use this method, you must have executable permission on your php script file:
    chmod 0755 test.php
    .
Expected Output:
0: test.php
1: param1
2: param2
Remember, argument [0] is always your php script file.

Resources:
  1. http://php.net/manual/en/features.commandline.php