我想直接用命令行执行一条PHP语句,比如if(function_exists("my_func")) echo 'function exists';
,而不必使用单独的PHP文件.
这怎么可能呢?
我想直接用命令行执行一条PHP语句,比如if(function_exists("my_func")) echo 'function exists';
,而不必使用单独的PHP文件.
这怎么可能呢?
If you're going to do PHP in the command line, I recommend you install 100.这更有趣.
无论如何,php
命令提供two switches to execute code from the command line:
-r <code> Run PHP <code> without using script tags <?..?>
-R <code> Run PHP <code> for every input line
你可以这样使用php
's -r switch:
php -r 'echo function_exists("foo") ? "yes" : "no";'
上面的PHP命令应该是output no
和returns 0
,如您所见:
>>> php -r 'echo function_exists("foo") ? "yes" : "no";'
no
>>> echo $? # print the return value of the previous command
0
另一个有趣的switch 是php -a:
-a Run as interactive shell
它是sort of lame compared to 100,但如果你不想安装the awesome interactive shell for PHP made by Facebook to get tab completion, history, and so on,那么use -a as such:
>>> php -a
Interactive shell
php > echo function_exists("foo") ? "yes" : "no";
no
php >
If it doesn't work在你的盒子上,就像我的盒子es(tested在Ubuntu和Arch Linux上),然后是probably your PHP setup is fuzzy or broken.如果运行此命令:
php -i | grep 'API'
你看:
Server API => Command Line Interface
If you don't,这意味着maybe another command will provides the CLI SAPI.试试php cli;也许它是你的操作系统中可用的一个包或命令.
If you do确保您的php
命令使用CLI(命令行界面)SAPI(服务器API),然后运行php -h | grep code
到find out which crazy switch - as this hasn't changed for year-允许在您的版本/设置中运行代码.
另外两个例子,只是为了确保它在我的盒子上工作:
>>> php -r 'echo function_exists("sg_load") ? "yes" : "no";'
no
>>> php -r 'echo function_exists("print_r") ? "yes" : "no";'
yes
另外,请注意,扩展可能是在CLI中加载的,而不是在CGI或Apache SAPI中加载的.It is likely that several PHP SAPIs use different php.ini files,例如,Gentoo Linux盒上的/etc/php/cli/php.ini
对/etc/php/cgi/php.ini
对/etc/php/apache/php.ini
.找出哪个ini文件与php -i | grep ini
一起使用.