I’m writing an script that is able to read from stdin and then request 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 script.php
inputdata
^D
Are you sure?
But I’m trying to run it using a file as STDIN. In that case, readline() returns false and no confirmation is prompted.
$ php script.php < data.txt
or
$ echo "foobar" | php script.php
How can I read both from the STDIN and keyboard when invoking this script in this way?
Thanks.
Use fgetc function with
STDIN. See example bellow.Console output
Sample 1
Sample 2