CLI : Take "masked" input from STDIN ?

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
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

CLI : Take "masked" input from STDIN ?

Post by Chris Corbyn »

I want to take a password from STDIN for a command line tool I'm making.
Being a password I don't want the text to be displayed as it is typed...
Can I do that with PHP for CLI?

Example:

Code: Select all

echo "New Password: ";
$pass = trim(fgets(STDIN));
echo "Confirm Password: ";
$pass2 = trim(fgets(STDIN));
If I can have NOTHING printed at all (unix style) that'd be great, but starred out is also OK.

Cheers,

d11
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Post by onion2k »

I don't think you can do that with vanilla PHP. There might be an extension to help out though.

Or, super long shot, you might be able to set the STDIN stream as non-blocking, detect when a character comes in, then use fputs(STDOUT) to print a backspace followed by a * .. Tricky to code that though.
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

I'll give that a go... doesn't sound overly tricky if PHP has those abailites ;)

Thanks
User avatar
anjanesh
DevNet Resident
Posts: 1679
Joined: Sat Dec 06, 2003 9:52 pm
Location: Mumbai, India

Post by anjanesh »

Is there no C version of getch() ? Getting a character at a time not displaying it ?
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post by timvw »

Here is a *nix solution ;) Meaby you can do the same in windows with ECHO on/off

Code: Select all

function ttyecho($on)
{
  global $ttyecho;
  
  if($on)
  {
    if(isset($ttyecho))
    {
      exec("stty $ttyecho");
    }
  }
  else
  {
    $ttyecho = exec("stty -g");
    exec("stty -echo");
  }
}

ttyecho(false); //turn off echoing
echo "\nEnter your password: ";
$password = trim(fgets(STDIN)); 
echo "\nYour password: $password\n";
ttyecho(true); //turn echoing back on
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

Thanks tim... works a treat. I don't need to have it windows compatible. It's a tool for setting up unix-only software anyway ;)
Post Reply