Pre-populate STDIN

Hi! Please consider following:

#!/usr/bin/php
<?php
fwrite(STDOUT, "Please enter something:\n");
$answer = trim(fgets(STDIN));
echo "$answer\n";
?>

Open in new window


Is it possible to pre-populate a default value here in STDIN?
LVL 21
Julian MatzJoint ChairpersonAsked:
Who is Participating?
 
Ray PaseurCommented:
Maybe something like this would make sense for your app.
#!/usr/bin/php
<?php
fwrite(STDOUT, "Please enter something:\n");
$answer = trim(fgets(STDIN));

if (empty($answer)) $answer = 'PREPOPULATED ANSWER';

echo "$answer\n";
?>

Open in new window

0
 
arnoldCommented:
echo "data for STDIN" | your_php_script
your_php_script < "filename"
The data from the filename will be available on STDIN.
0
 
BasementCatCommented:
You can't "pre-populate" STDIN since it's a file handle, but what Ray suggested will work.  The only way to "pre-populate" stdin would be to pipe some input to the program ahead of time, like
echo "hello, world" |yourprogram.php

Open in new window

0
 
Julian MatzJoint ChairpersonAuthor Commented:
Thanks, I thought of the if (empty($answer)) solution afterwards. It will work for me. I just have the default answer in brackets after the question.

Thanks for your help.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.