0

I am making a script that accepts data input both via:

  1. filename (it opens a .txt file for reading)
  2. pipe (reading via "php://stdin")

In both cases, I need to get controls from keyboard, stdin;

1. When opening the file not using pipe(stdin) I can read the keyboard from

./myscript.php --file filename.txt

then

<?php

$DATA = file_get_contents("filename.txt");
// etc loop
$input = fopen("php://stdin", "r"); // works
stream_set_blocking($input, false);
$key = fgetc($input); // get input from keyboard
echo $key;

?>

2. But when using pipe, this does not work, example:

cat filename.txt | ./myscript.php

then

<?php

$DATA = file_get_contents("php://stdin");
// etc loop
$input = fopen("php://stdin", "r"); // does not works
stream_set_blocking($input, false);
$key = fgetc($input); // get input from keyboard
echo $key;

?>

Why can't I read from keyboard in the second case? Thanks.

Iacchus
  • 2,671
  • 2
  • 29
  • 24

1 Answers1

0

I was able to do it reading directly from /dev/tty

<?php

$DATA = file_get_contents("php://stdin");
// etc loop
$input = fopen("/dev/tty", "r"); // this works, as stdin == pipe
stream_set_blocking($input, false);
$key = fgetc($input); // get input from keyboard
echo $key;

?>

I found the answer here:

How to make Perl use different handles for pipe input and keyboard input?

Also:

Can I prompt for user input after reading piped input on STDIN in Perl?

Community
  • 1
  • 1
Iacchus
  • 2,671
  • 2
  • 29
  • 24