Page 1 of 1

PHP Command Line - Hiding User Input

Posted: Tue Oct 24, 2006 11:02 am
by Jus144tice
I have a command line php program and during execution I ask the user for a username and password. I would like to make it so that when the user enters the password, it does not get "echoed" out to the screen as it is being typed. Any suggesstions? In PERL I could do:

Code: Select all

use Term::ReadKey qw (ReadMode);
ReadMode('noecho');
$password = <STDIN>;
ReadMode('restore');

Posted: Tue Oct 24, 2006 1:34 pm
by volka
The readline extension might provide something like that. I will look into it.
http://de2.php.net/readline

edit: readline doesn't seem to have such an option. Sorry, no clue.

Posted: Tue Oct 24, 2006 3:57 pm
by Jus144tice
In case anyone is interested, I did find a way to do this. You can use the ncurses library as follows:

Code: Select all

ncurses_noecho();
$password = trim(fgets(STDIN));
ncurses_echo();
But, of course, we do not have the ncurses library installed here so I cannot use this. So, if anyone finds an alternative way to do this, I am still interested.

Posted: Wed Oct 25, 2006 4:31 pm
by Jus144tice
Again, if anyone is interested - here is how this can be done - this time without using the ncurses library.

from http://www.php.net/manual/en/function.readline.php
TheFatherMind At Dangerous-Minds.NET
02-Mar-2004 11:22
Above I took what "christian at gaeking dot de" did and I upgraded it a bit. Rewrote it to my needs in the process. I found one minor bug with what he was doing and I also improved on it....

The bug with what he had is that when you hit the keyboard "Return" key it takes that with the varible. So if you type in 123 it takes "123\n". I needed to detect blank input so I purge off the "\n" on the end to fix it.

The Enhancement. I added some options to the "read". One is that if you optionally specify True for the second option on the ReadText function, it will NOT show what you type. This is good for grabbing passwords. Also I added -er to the options of "read". "-e" allows for standard input coming from the terminal (I use this for shell scripts). Also "-r" turns off the backslash incase you want that as part of your input. This means you can not escape any thing while doing input. Feel free to change the options though. And finally I added the ability to prompt with the input.

Code: Select all

<?php
  Function ReadText($Prompt,$Silent=False){
   $Options="-er";
   If($Silent==True){
     $Options=$Options." -s";
   }
   $Returned=POpen("read $Options -p \"$Prompt\"; echo \$REPLY","r");
   $TextEntered=FGets($Returned,100);
   PClose($Returned);
   $TextEntered=SubStr($TextEntered,0,StrLen($TextEntered)-1-1);
   If($Silent==True){
     Print "\n";
     @OB_Flush();
     Flush();
   }
   Return $TextEntered;
  }
?>