Linux 在命令行中运行 php 代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6965541/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Run php code in command line
提问by kaiseroskilo
I just began learning php. I've installed php5
on linux and wrote very simple code just to get going.
我刚开始学习php。我已经php5
在 linux上安装并编写了非常简单的代码来开始工作。
How can I run scripts? I tried using the -f
option but it works as a cat
command and just spits out the code to STDOUT
.
如何运行脚本?我尝试使用该-f
选项,但它作为cat
命令工作,只是将代码吐出到STDOUT
.
The interactive interpreter option works fine. Is a web browser the only way to execute a PHP script?
交互式解释器选项工作正常。Web 浏览器是执行 PHP 脚本的唯一方法吗?
采纳答案by Quentin
A simple:
一个简单的:
php myScript.php
… should do the job.
......应该做这项工作。
If it is acting like cat, then you probably forgot to switch out of template mode and into script mode with <?php
如果它表现得像 cat,那么您可能忘记使用以下命令从模板模式切换到脚本模式 <?php
回答by Tadeck
Actually, PHP's main purpose is to generate web pages, but there are at least two other options:
实际上,PHP 的主要目的是生成网页,但至少还有两个其他选择:
- command line (CLI) script execution,
- interactive shell- which is actually the variant of the previous option,
- 命令行 (CLI) 脚本执行,
- 交互式 shell- 这实际上是前一个选项的变体,
The first one can be achieved in many ways (eg. by giving proper permissions to the file and calling script by providing its URI, eg. ./index.php
), the second one can be invoked by php -a
command (as stated in the documentation mentioned above).
第一个可以通过多种方式实现(例如,通过为文件提供适当的权限并通过提供其 URI 调用脚本,例如./index.php
),第二个可以通过php -a
命令调用(如上述文档中所述)。
回答by Jarrod
As already mentioned, you can execute your PHP with the following.
如前所述,您可以使用以下命令执行 PHP。
$ php myScript.php
If you wish to pass an argument(s), you can simply do so like this:
如果你想传递一个参数,你可以简单地这样做:
$ php myScript.php Apples
In your PHP file you can use this argument by accessing the $argv array like this:
在您的 PHP 文件中,您可以通过访问 $argv 数组来使用此参数,如下所示:
<?php
echo 'I like ' . $argv[1];
?>
The above would print our "I like Apples". Note the array index is 1 and not 0. 0 is used for script name. In this case $argv would be "myScript.php"
以上将打印我们的“我喜欢苹果”。请注意,数组索引是 1 而不是 0。0 用于脚本名称。在这种情况下 $argv 将是“myScript.php”
For more info check out my blog post Running PHP from the Command Line - Basics
有关更多信息,请查看我的博客文章Running PHP from the Command Line - Basics
回答by Jadeye
Shorter way for command line:
命令行的更短方法:
php -r 'echo "Hello "; echo "Jay";'
ORphp -r 'echo dirname("parent/child/reply") . "\n";'
php -r 'echo "Hello "; echo "Jay";'
或者php -r 'echo dirname("parent/child/reply") . "\n";'