PHP and Command Line
PHP is probably the best language to talk with web. But it isn’t good when you need to work with command line. When I started work with SugarCRM I’ve discovered that about 40% of tasks like synchronization with related systems, massive updates etc should be done in the command line and not via HTTP. There are my suggestions based on my experience (it is not so wide of course ;)).
To run PHP script from command line you just need to run following:
>PHP example.php
To have possibility to run PHP script without typing PHP let’s add path to the interpretaror in the begging of the script:
#!/usr/bin/php < ?php echo "Hello World!"; ?>
Now to run PHP script we need to type just its name:
>./example.php
Note : Be sure the script is execvutable (chmod +x example.php)
Well, let’s suppose we need to send some argument to our script. PHP has a variable $argc which contains a nuber of input arguments and array $argv which contains input arguments essentially. Notice that $argv[0] is the script name (it’s terribly and not obviously). Therefore we should use index started from 1 to get out arguments:
#!/usr/bin/php
< ?php
echo "Hello, dear ".$argv[1]."!\n";
?>
If we run our script like that
>./example.php Michael
we see following result
>Hello, dear Michael!
One thing you should know to work with command line. You have to compile PHP with CLI support:
--enable-CLI
That option is set in true by default. But who knows probably your system administrator disabled it. If CLI support switched off and you don’t want to recompile PHP you can access to the command line parameters via global array $_SERVER:
#!/usr/bin/php
< ?php
echo "Hello, dear ".$_SERVER['argv'][1]."!\n";
?>
Maybe, it’s not perfect but it’s working!
One suggestion at the end: be sure that it is defined enough memory and run time in your PHP.ini:
max_execution_time = 120 ; I work with SOAP and my script crashed before I changed it
memory_limit = 50M ; SugarCRM has very heavy objects and it needs at least that value