Saturday, December 27, 2014

How to execute PHP code from the command line?

If you're going to do PHP in the command line, i recommend you install phpsh, a decent PHP shell.It's a lot more fun.
Anyway, the php command offers two switches to execute code from the command line:
-r         Run PHP  without using script tags 
-R         Run PHP  for every input line
You can use php's -r switch as such:
php -r 'echo function_exists("foo") ? "yes" : "no";'
The above PHP command above should output no and returns 0 as you can see:
>>> php -r 'echo function_exists("foo") ? "yes" : "no";'
>>> echo $? # print the return value of the previous command
Another funny switch is php -a:
-a               Run as interactive shell
It's sort of lame compared to phpsh, but if you don't want to install the awesome interactive shell for php made by facebook to get tab completion, history, and so on, then use -a as such:
>>> php -a
Interactive shell

php > echo function_exists("foo") ? "yes" : "no";
php > 
If it doesn't work on your box like on my box*es* (tested on Ubuntu and Arch), then probably your PHP setup is fuzzy or broken. If you run this command:
php -i | grep 'API'
You should see:
Server API => Command Line Interface
If you don't, this means that maybe another command will provides the CLI SAPI. Try php-cli, maybe it's a package or a command available in your OS.
If you do see that your php command uses the CLI (Command Line Interface) SAPI (Server API), then run php -h | grep code to find out which crazy switch - as this hasn't changed for year- allows to run code in your version/setup.
Another couple of examples, just to make sure it works on my boxes:
>>> php -r 'echo function_exists("sg_load") ? "yes" : "no";' 
>>> php -r 'echo function_exists("print_r") ? "yes" : "no";' 
Also, note that it is possible that an extension is loaded in the CLI and not in the CGI or Apache SAPI. It is likely that several PHP SAPIs use different php.ini files, e.g. /etc/php/cli/php.ini vs /etc/php/cgi/php.ini vs /etc/php/apache/php.ini on a Gentoo box. Find out which ini file is used with php -i | grep ini.

No comments: