PHP cli从用户那里获取输入然后转储到变量中可能吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6543841/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:41:18  来源:igfitidea点击:

PHP cli getting input from user and then dumping into variable possible?

php

提问by kritya

Is it possible to get input from a user using php cli and then dump the input into a variable and then the script goes ahead.

是否可以使用 php cli 从用户那里获取输入,然后将输入转储到变量中,然后脚本继续运行。

Just like the c++ cinfunction ?

就像 c++cin函数一样?

Is that possible if yes then how ? Maybe not only php but maybe with some linux commands ?

如果是,那有可能吗?也许不仅是 php,也许还有一些 linux 命令?

回答by anubhava

You can simply do:

你可以简单地做:

$line = fgets(STDIN);

to read a line from standard input in php CLI mode.

在 php CLI 模式下从标准输入读取一行。

回答by Devraj

Have a look at this PHP manual page http://php.net/manual/en/features.commandline.php

看看这个 PHP 手册页 http://php.net/manual/en/features.commandline.php

in particular

特别是

<?php
echo "Are you sure you want to do this?  Type 'yes' to continue: ";
$handle = fopen ("php://stdin","r");
$line = fgets($handle);
if(trim($line) != 'yes'){
    echo "ABORTING!\n";
    exit;
}
echo "\n";
echo "Thank you, continuing...\n";
?>

回答by Niko9911

In this example I'm extending Devjar's example. Credits for him for example code. Last code example is simplest and safest in my opinion.

在这个例子中,我扩展了 Devjar 的例子。例如代码他的学分。在我看来,最后一个代码示例是最简单和最安全的。

When you use his code:

当你使用他的代码时:

<?php
echo "Are you sure you want to do this?  Type 'yes' to continue: ";
$handle = fopen ("php://stdin","r");
$line = fgets($handle);
if(trim($line) != 'yes'){
echo "ABORTING!\n";
exit;
}
echo "\n";
echo "Thank you, continuing...\n";
?>

You should note stdin mode is notbinary-safe. You should add "b" to your mode and use following code:

您应该注意 stdin 模式不是二进制安全的。您应该将“b”添加到您的模式并使用以下代码:

<?php
echo "Are you sure you want to do this?  Type 'yes' to continue: ";
$handle = fopen ("php://stdin","rb"); // <-- Add "b" Here for Binary-Safe
$line = fgets($handle);
if(trim($line) != 'yes'){
echo "ABORTING!\n";
exit;
}
echo "\n";
echo "Thank you, continuing...\n";
?>

Also you can set max charters. This is my personal example. I'll suggest to use this as your code. It's also recommended to use directly STDIN than "php://stdin".

您也可以设置最大包机。这是我个人的例子。我建议将其用作您的代码。还建议直接使用 STDIN 而不是“php://stdin”。

<?php
/* Define STDIN in case if it is not already defined by PHP for some reason */
if(!defined("STDIN")) {
define("STDIN", fopen('php://stdin','rb'))
}

echo "Hello! What is your name (enter below):\n";
$strName = fread(STDIN, 80); // Read up to 80 characters or a newline
echo 'Hello ' , $strName , "\n";
?>