20.4. Reading Passwords
Problem
You need to read a string from the command line without it being echoed as it’s typed; for example, when entering passwords.
Solution
On Unix systems, use /bin/stty to toggle echoing of typed characters:
// turn off echo `/bin/stty -echo`; // read password $password = readline(); // turn echo back on `/bin/stty echo`;
On Windows, use w32api_register_function( ) to
import _getch( ) from
msvcrt.dll:
// load the w32api extension and register _getch()
dl('php_w32api.dll');
w32api_register_function('msvcrt.dll','_getch','int');
while(true) {
// get a character from the keyboard
$c = chr(_getch());
if ( "\r" == $c || "\n" == $c ) {
// if it's a newline, break out of the loop, we've got our password
break;
} elseif ("\x08" == $c) {
/* if it's a backspace, delete the previous char from $password */
$password = substr_replace($password,'',-1,1);
} elseif ("\x03" == $c) {
// if it's Control-C, clear $password and break out of the loop
$password = NULL;
break;
} else {
// otherwise, add the character to the password
$password .= $c;
}
}Discussion
On Unix, you use
/bin/stty
to control the terminal
characteristics so that typed characters aren’t
echoed to the screen while you read a password.
Windows doesn’t have
/bin/stty, so you use the W32api extension to
get access
_getch( ) in the Microsoft C runtime library,
msvcrt.dll. The _getch( ) function reads a character without echoing it to the screen. It returns the ASCII code of the character read, so you convert ...