I know that there will be people who read this and say, “well of course, you can do that”. But I also know that there others who, like me, worked with PHP for many years unaware that you could execute PHP directly from the command line without the need for a script.
But why would you want to?
Well I find it incredibly useful for very quickly understanding the sort of response I’m likely to get from standard PHP functions. So for example:
php -r 'echo date("W") % 2;'
will confirm that that the PHP expression between the quotes will tell me whether it’s an odd or an even week (from the beginning of the year). (Yes I have a real reason for wanting to know this
Did you notice that semi colon inside the quotes. Yep, that means that you can string together multiple PHP statements for execution. Like this …
php -r '$a=["x"=>1,"y"=>2]; $b=["x"=>3,"z"=>4]; $c=array_merge($a,$b); print_r($c);'
Of course, this is pushing the limits of good sense somewhat, and more statements than this might be better in a script, in which case the “f” flag will cause that script to be parsed and executed:
php -f myscript.php
Better still, you can also add parameters and pick them up inside the script as $_GET variables. For example:
php -f myscript.php a=1 b=2
would populate $_GET[‘a’] and $_GET[‘b’].
Also helpful is the “i” flag which streams information about the local PHP installation (that more usually seen when phpinfo is executed). I’ve found this very useful in combination with grep for checking out memory limits and installed modules. This is the sort of thing I mean:
php -i | grep memory_limit
php -i | grep timezone
php -i | grep gzip
And I’m just scratching the surface. For more information about command line PHP, take a look at the manual.