PHP readline () when STDIN is different from keyboard

I am writing a script that can read from stdin and then ask for confirmation.

<?php $stream = fopen('php://stdin', 'r'); $input = fgets($stream, 1024); $confirmation = readline('Are you sure?'); if ( $confirmation == 'y' ) /* Do dangerous stuff */ 

When I run it directly:

 $ PHP .php inputdata ^D Are you sure? 

But I'm trying to run it using the file as STDIN. In this case, readline () returns false and no confirmation is requested.

 $ PHP .php < data.txt 

or

 $ echo "foobar" | PHP .php 

How can I read both from STDIN and keyboard when calling this script this way?

Thanks.

+4
source share
2 answers

Use the fgetc STDIN function. See the example below.

 $input = fgets(STDIN, 1024); echo "\nAre you sure?\n"; $conf = fgetc(STDIN); if($conf=='y'){ echo "Great! Lets go ahead\n"; }else{ echo "Okay, May be next time\n"; } 

Console exit

Example 1

  $ echo 'data > y > ' | php php_readline.php Are you sure? Great! Lets go ahead 

Sample 2

 $ php php_readline.php Some data Are you sure? n Okay, May be next time 
+6
source

According to the comment on the PHP page ( http://php.net/manual/en/book.readline.php ):

When readline is enabled, php switches to terminal mode to accept line buffered input. This means that the correct way to use cli when you connect to an interactive command, you must explicitly indicate that php does not use the terminal for input:

php somescript.php </ dev / null | less

I think you need to add | less | less . Without knowing the structure of your data, perhaps something may be needed in your script to handle the transition from data to confirmation.

You can add a mechanism to detect when line-buffered input is enabled.

+3
source

Source: https://habr.com/ru/post/1398857/


All Articles