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?
This question is related to
php
linux
function
shell
command-line
Using PHP from the command line
Use "
instead of '
on Windows when using the CLI version with -r
:
php -r "echo 1;"
-- correct
php -r 'echo 1;'
-- incorrect
PHP Parse error: syntax error, unexpected ''echo' (T_ENCAPSED_AND_WHITESPACE), expecting end of file in Command line code on line 1
Don't forget the semicolon to close the line.
On the command line:
php -i | grep sourceguardian
If it's there, then you'll get some text. If not, you won't get a thing.
You can use:
echo '<?php if(function_exists("my_func")) echo "function exists"; ' | php
The short tag "< ?=" can be helpful too:
echo '<?= function_exists("foo") ? "yes" : "no";' | php
echo '<?= 8+7+9 ;' | php
The closing tag "?>" is optional, but don't forget the final ";"!
If you're using Laravel, you can use php artisan tinker
to get an amazing interactive shell to interact with your Laravel app. However, Tinker works with "Psysh" under the hood which is a popular PHP REPL and you can use it even if you're not using Laravel (bare PHP):
// Bare PHP:
>>> preg_match("/hell/", "hello");
=> 1
// Laravel Stuff:
>>> Str::slug("How to get the job done?!!?!", "_");
=> "how_to_get_the_job_done"
One great feature I really like about Psysh is that it provides a quick way for directly looking up the PHP docs from the command line. To get it to work, you only have to take the following simple steps:
apt install php-sqlite3
And then get the required PHP documentation database and move it to the proper location:
wget http://psysh.org/manual/en/php_manual.sqlite
mkdir -p /usr/local/share/psysh/ && mv php_manual.sqlite /usr/local/share/psysh/
Now for instance:
Source: Stackoverflow.com