PHP cli从用户获取输入,然后转储到变量中是否可能?
是否可以使用php cli从用户处获取输入,然后将输入转储到变量中,然后脚本继续执行 < >就像C++ <代码> CIN < /代码>函数? 如果可以,那怎么办?PHP cli从用户获取输入,然后转储到变量中是否可能?,php,Php,是否可以使用php cli从用户处获取输入,然后将输入转储到变量中,然后脚本继续执行 < >就像C++ CIN < /代码>函数? 如果可以,那怎么办? 可能不仅仅是php,还可能使用一些linux命令?看看这个php手册页面 特别是 <?php echo "Are you sure you want to do this? Type 'yes' to continue: "; $handle = fopen ("php://stdin","r"); $line = fgets($h
可能不仅仅是php,还可能使用一些linux命令?看看这个php手册页面 特别是
<?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";
?>
您只需执行以下操作:
$line = fgets(STDIN);
在php CLI模式下从标准输入读取一行。在本例中,我扩展了Devjar的示例。例如,他的学分代码。在我看来,最后一个代码示例是最简单和最安全的
当您使用他的代码时:
<?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";
?>
类似地,您可以创建一个函数,如python
$line = input("Please put in a number: ");
if ($line === 20){
echo true;
} else {
echo false;
}
function input(string $prompt = null): string
{
echo $prompt;
$handle = fopen ("php://stdin","r");
$output = fgets ($handle);
return trim ($output);
}
工作,但有更好的方法吗?作为ofc,读取该文件将使程序降低一些什么,但如果这是唯一的方式,我非常喜欢你的答案:P@kritya-如果您选择此方法,我唯一的建议是使用STDIN
常量而不是“php://stdin"按照中的建议。编写一个获取输入并重用函数的函数。只需像这样附加另一行:$line2=fgets(STDIN)如果您想在循环中读取代码,直到EOF,那么使用while(FALSE!=($line=fgets(STDIN)){echo“line=$line”;}
STDIN
并不总是定义的,所以接受的答案更好。在核心php>5.3.6的源代码中,它被定义为:define('STDIN',fopen('php://stdin","r"),;定义('STDOUT',fopen('php://stdout","w"),;定义('STDERR',fopen('php://stderr","w"),代码>
<?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";
?>
$line = input("Please put in a number: ");
if ($line === 20){
echo true;
} else {
echo false;
}
function input(string $prompt = null): string
{
echo $prompt;
$handle = fopen ("php://stdin","r");
$output = fgets ($handle);
return trim ($output);
}