2010-05-28 34 views
16

我想編寫一個我可以從命令行使用的php腳本。我希望它提示並接受一些項目的輸入,然後吐出一些結果。我想在php中這樣做,因爲我所有的類和庫都在php中,我只是想爲一些簡單的命令行界面做一些事情。我該如何編寫一個命令行交互式php腳本?

提示和接受重複的命令行輸入是絆倒我的部分。我該怎麼做呢?

回答

12

PHP: Read from Keyboard – Get User Input from Keyboard Console by Typing

你需要一個特殊的文件:php://stdin代表標準輸入。

print "Type your message. Type '.' on a line by itself when you're done.\n"; 

$fp = fopen('php://stdin', 'r'); 
$last_line = false; 
$message = ''; 
while (!$last_line) { 
    $next_line = fgets($fp, 1024); // read the special file to get the user input from keyboard 
    if (".\n" == $next_line) { 
     $last_line = true; 
    } else { 
     $message .= $next_line; 
    } 
} 
17

從PHP手冊中的I/O Streams頁描述瞭如何使用標準輸入讀取命令行的一行:

<?php 
$line = trim(fgets(STDIN)); // reads one line from STDIN 
fscanf(STDIN, "%d\n", $number); // reads number from STDIN 
?> 
1

的算法很簡單:

until done: 
    display prompt 
    line := read a command line of input 
    handle line 

這是非常瑣碎的使用映射命令回調處理這些功能的陣列()。整個挑戰大致是一段時間的循環,並且有兩個函數調用,PHP對於更高級的shell應用程序也有readline interface

+0

「讀取輸入命令行」部分將我啓程。你如何獲得它不斷輪詢用戶輸入? – user151841 2010-05-28 14:07:57

+0

正常情況下,它會像while($ line = readline($ promptstring));細節基本上等於你想要的那種錯誤檢查,以及用戶要求退出的方式。 查看手冊中的fgets()和readline()函數。 – TerryP 2010-05-28 19:29:06

9

我不知道你的輸入可能多麼複雜,但readline是處理它的交互CLI程序的最佳方式。

你會從你的shell中獲得相同的生物,比如命令歷史。

使用它很簡單:

$command = readline("Enter Command: "); 
/* Then add the input to the command history */ 
readline_add_history($command); 

If available,它確實使簡單。代碼

+0

實現簡單[CLI - 命令行界面](https://en.wikipedia.org/wiki/Command-line_interface)的最佳方法! – 2017-08-08 16:06:27

1

簡單:

#!/usr/bin/php 
<?php 
define('CONFIRMED_NO', 1); 

while (1) { 
    fputs(STDOUT, "\n"."***WARNING***: This action causes permanent data deletion.\nAre you sure you're not going to wine about it later? [y,n]: "); 

    $response = strtolower(trim(fgets(STDIN))); 
    if($response == 'y') { 
     break; 
    } elseif($response == 'n') { 
     echo "\n",'So I guess you changed your mind eh?', "\n"; 
     exit (CONFIRMED_NO); 
    } else { 
     echo "\n", "Dude, that's not an option you idiot. Let's try this again.", "\n"; 
     continue; 
    } 
} 

echo "\n","You're very brave. Let's continue with what we wanted to do.", "\n\n"; 
相關問題