I would like to execute a single PHP statement like if(function_exists("my_func")) echo 'function exists'; directly with the command line without having to use a separate PHP file.
How is it possible?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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
phpcommand offers two switches to execute code from the command line:You can use
php‘s -r switch as such:The above PHP command above should output
noand returns0as you can see:Another funny switch is php -a:
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:
If it doesn’t work on your box like on my boxes (tested on Ubuntu and Arch Linux), then probably your PHP setup is fuzzy or broken. If you run this command:
You should see:
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
phpcommand uses the CLI (command-line interface) SAPI (Server API), then runphp -h | grep codeto 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:
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.inivs./etc/php/cgi/php.inivs./etc/php/apache/php.inion a Gentoo Linux box. Find out which ini file is used withphp -i | grep ini.