在命令行上执行一串 PHP 代码

2022-08-30 08:33:21

我希望能够在命令行上运行一行PHP代码,类似于以下选项的工作方式:

perl -e "print 'hi';"
python -c "print 'hi'"
ruby -e "puts 'hi'"

我希望能够做到:

php "echo 'hi';"

我已经读到有一个选项可以做我需要的php,但是当我尝试使用它时,它似乎不可用。我尝试过使用PHP 5.2.13和PHP 4.4.9,但都没有可用的选项。-r-r

我写了这个脚本(我称之为run_php.php) - 它有效,但我不是它的忠实粉丝,只是因为我觉得应该有一个更“正确”的方式来做到这一点。

#!/usr/bin/php5 -q
<?php echo eval($argv[1]); ?>

有选择吗?如果是这样,为什么在我运行时它不可用?如果没有选项,最好的方法是什么(如果可能的话,无需编写中间脚本)?-r--help-r


因为我不认为上面很清楚,所以我无法使用该选项。以下是我正在运行的两个版本的PHP的输出。-rphp -h

4.4.9 菲律宾比索

Usage: php [-q] [-h] [-s] [-v] [-i] [-f <file>]
       php <file> [args...]
  -a               Run interactively
  -C               Do not chdir to the script's directory
  -c <path>|<file> Look for php.ini file in this directory
  -n               No php.ini file will be used
  -d foo[=bar]     Define INI entry foo with value 'bar'
  -e               Generate extended information for debugger/profiler
  -f <file>        Parse <file>.  Implies `-q'
  -h               This help
  -i               PHP information
  -l               Syntax check only (lint)
  -m               Show compiled in modules
  -q               Quiet-mode.  Suppress HTTP Header output.
  -s               Display colour syntax highlighted source.
  -v               Version number
  -w               Display source with stripped comments and whitespace.
  -z <file>        Load Zend extension <file>.

5.2.13 菲律宾比索

Usage: php [-q] [-h] [-s] [-v] [-i] [-f <file>]
       php <file> [args...]
  -a               Run interactively
  -C               Do not chdir to the script's directory
  -c <path>|<file> Look for php.ini file in this directory
  -n               No php.ini file will be used
  -d foo[=bar]     Define INI entry foo with value 'bar'
  -e               Generate extended information for debugger/profiler
  -f <file>        Parse <file>.  Implies `-q'
  -h               This help
  -i               PHP information
  -l               Syntax check only (lint)
  -m               Show compiled in modules
  -q               Quiet-mode.  Suppress HTTP Header output.
  -s               Display colour syntax highlighted source.
  -v               Version number
  -w               Display source with stripped comments and whitespace.
  -z <file>        Load Zend extension <file>.

没有 -r 选项。当我尝试使用该选项时,我得到:-r

参数 1 中的错误,字符 2:找不到选项 r

很抱歉造成混淆。


答案 1

是的,它在 PHP 5.2 的 cli SAPI 中就有。

如果你无法升级,并且 PHP 5.2 中没有这样的选项(我手头没有它来测试),你可以这样做:

echo "<?php echo \"hi\\n\";" | php

hi

源语言:

确实有一个选项(虽然我不确定PHP 5.2):-r

php -r "echo 'hi';";

hi

只需确保您使用的是PHP的命令行版本。 应该给你这样的东西(注意“cli”):php --version

php --version

PHP 5.3.0 (cli) (built: May 20 2010 19:05:12) (DEBUG)
Copyright (c) 1997-2009 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2009 Zend Technologies

答案 2

在新版本的PHP中,您只需键入“php -a”,然后跳入交互模式,您可以在其中尝试PHP。


推荐