2011-07-01 13 views

回答

58

看一看這個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"; 
?> 
+0

工程,但任何更好的方法? – kritya

+0

作爲ofc閱讀該文件將使程序一些whatslower – kritya

+0

但如果這是我非常喜歡你的答案:P – kritya

72

你可以簡單地做:

$line = fgets(STDIN); 

閱讀從標準線在php CLI模式下輸入。

+0

如何從它讀取超過1個輸入? – kritya

+1

只需附加另一行,如下所示:'$ line2 = fgets(STDIN);' – anubhava

+2

如果你想讀一個循環直到EOF,然後使用'while(FALSE!==($ line = fgets(STDIN))){ echo「line = $ line」; }' – anubhava

2

在這個例子中,我擴展了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"; 
?> 

你應該注意標準輸入模式不是二進制安全的。您應該在您的模式中添加「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"; 
?> 

您還可以設置最大章程。這是我個人的例子。我會建議使用這個作爲你的代碼。還建議直接使用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"; 
?> 
相關問題