Forum Moderators: coopster

Message Too Old, No Replies

Shell Scripting with PHP

         

mechanical messiah

8:36 pm on Jun 5, 2004 (gmt 0)

10+ Year Member



I have a shell program that uses the following code:


function read()
{
$fp = fopen("/dev/stdin", "r");
$input = fgets($fp, 255);
fclose($fp);

return str_replace("\n", "", $input);
}

print("\nYour name: ");
$name = read();

print("\n".$name);

Of course, this program just asks the user for their name, and then it prints it back to them. The problem is that the program immediately waits for input, but never prints the desired text. After entering input, it prints the desired text. This, of course, is backwards!

Is there a way to force the system to first print the desired text, THEN wait for input?

Thanks!

coopster

8:43 pm on Jun 5, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Have you tried to flush() [php.net] it first?

print("\nYour name: ");
flush();
$name = read();

mechanical messiah

9:01 pm on Jun 5, 2004 (gmt 0)

10+ Year Member



Doesn't seem to be working... "INPUT" is what I typed when the script paused...


dustin@aexon:~/bin/testing$ testing123.php
INPUT

Your name:
INPUT
dustin@aexon:~/bin/testing$

It should also be noted what happens when I run the script using "php filename.php"...


dustin@aexon:~/bin/zips$ php testing123.php
INPUT
Content-type: text/html
X-Powered-By: PHP/4.3.3

Your name:
INPUT
dustin@aexon:~/bin/zips$

Just to show you, here is the code being used:


#!/usr/bin/php -q
<?
function read()
{
$fp = fopen("/dev/stdin", "r");
$input = fgets($fp, 255);
fclose($fp);

return str_replace("\n", "", $input);
}

print("\nYour name: "); flush();
$name = read();

print("\n".$name."\n"); flush();

?>

coopster

10:43 pm on Jun 5, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



I didn't realize you were running from the command line. Have you read about Using PHP from the command line [php.net]?