Can PHP CLI perform cout/cin type Fuctionality?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
techniq
Forum Newbie
Posts: 6
Joined: Sat May 18, 2002 12:15 pm
Location: US

Can PHP CLI perform cout/cin type Fuctionality?

Post by techniq »

I would like to request user input from the CLI by prompting for it. Then they type it in and I could assign their input to a variable(s). Does php provide functionality like 'cout <<' & 'cin >>' ? If yes, can anyone tell me how.
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

a similar question has been posted here
and take a look here
especially "php://stdin", "php://stdout", or "php://stderr",
techniq
Forum Newbie
Posts: 6
Joined: Sat May 18, 2002 12:15 pm
Location: US

Post by techniq »

Thanks for replying. I've looked at sscanf() and see that it will read a string. How would I implement sscanf() and fopen() to do somthing llike this.

In other words can I duplicate this C++ code in PHP:

Code: Select all

void main() &#123;

     int age;

     cout << "\nPlease enter your age: "
     cin >>  age;

     if (age) &#123;
          cout << "\nYou are " << age << " years old!\n"
          << endl;
     &#125;
&#125;
Thanks!
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

Code: Select all

$handle = fopen("php://stdin", "r");
fscanf($handle, "%&#1111;0-9]", $age);
will read a number from stdin (I suppose - never done this ;) )
techniq
Forum Newbie
Posts: 6
Joined: Sat May 18, 2002 12:15 pm
Location: US

It works!!!

Post by techniq »

Thanks for the sample! It works perfect! :P

Since you've never tried it, I've supplied a working example that can be used from the CLI. Thanks again!

Code: Select all

<?
// Retrieve age from user input

$handle = fopen("php://stdin", "r");
echo "\nPlease enter your age: ";
fscanf($handle, "%&#1111;0-9]", &$age);
fclose($handle);
$age = $age + 10;
echo "\nYou will be $age years old in 10 years!\n";

?>
Post Reply