是否有可能使用php cli从用户那里获得输入,然后将输入转储到变量中,然后脚本继续运行.
就像c ++ cin
函数一样?
这是可能的,如果是,那么如何?也许不仅是php而且可能还有一些linux命令?
谢谢
anu*_*ava 87
你可以简单地做:
$line = fgets(STDIN);
Run Code Online (Sandbox Code Playgroud)
在php CLI模式下从标准输入读取一行.
Dev*_*raj 70
看看这个PHP手册页 http://php.net/manual/en/features.commandline.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";
?>
Run Code Online (Sandbox Code Playgroud)
在此示例中,我将扩展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";
?>
Run Code Online (Sandbox Code Playgroud)
您应该注意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";
?>
Run Code Online (Sandbox Code Playgroud)
您也可以设置最大包机。这是我的个人例子。我建议将其用作您的代码。还建议直接使用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";
?>
Run Code Online (Sandbox Code Playgroud)