The best and simplest way to get input from a user in the CLI with only PHP is to use fgetc() function with the STDIN constant:
<?php
echo 'Are you sure you want to quit? (y/n) ';
$input = fgetc(STDIN);
if ($input == 'y')
{
exit(0);
}
?>
fgetc
(PHP 4, PHP 5)
fgetc — ファイルポインタから1文字取り出す
説明
string fgetc
( resource $handle
)
指定したファイルポインタから 1 文字読み出します。
パラメータ
- handle
-
ファイルポインタは、有効なファイルポインタである必要があり、 fopen() または fsockopen() で正常にオープンされた (そしてまだ fclose() でクローズされていない) ファイルを指している必要があります。
返り値
handle が指すファイルポインタから 1 文字読み出し、 その文字からなる文字列を返します。EOF の場合に FALSE を返します。
例
例1 fgetc() の例
<?php
$fp = fopen('somefile.txt', 'r');
if (!$fp) {
echo 'somefile.txt をオープンできませんでした';
}
while (false !== ($char = fgetc($fp))) {
echo "$char\n";
}
?>
注意
注意: この関数はバイナリデータに対応しています。
参考
- fread() - バイナリセーフなファイルの読み込み
- fopen() - ファイルまたは URL をオープンする
- popen() - プロセスへのファイルポインタをオープンする
- fsockopen() - インターネット接続もしくはUnix ドメインソケット接続をオープンする
- fgets() - ファイルポインタから 1 行取得する
fgetc
alex at alexdemers dot me
12-May-2009 02:30
12-May-2009 02:30
ktraas at gmail dot com (Kevin Traas)
24-Mar-2009 12:08
24-Mar-2009 12:08
I was using command-line PHP to create an interactive script and wanted the user to enter just one character of input - in response a Yes/No question. Had some trouble finding a way to do so using fgets(), fgetc(), various suggestions using readline(), popen(), etc. Came up with the following that works quite nicely:
$ans = strtolower( trim( `bash -c "read -n 1 -t 10 ANS ; echo \\\$ANS"` ) );
