20.5. Reading Passwords20.5.1. ProblemYou need to read a string from the command line without it being echoed as it's typed; for example, when entering passwords. 20.5.2. SolutionOn 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:
20.5.3. DiscussionOn 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 it to a character using chr( ) . You then take action based on the character typed. If it's a newline or carriage return, you break out of the loop because the password has been entered. If it's a backspace, you delete a character from the end of the password. If it's a Control-C interrupt, you set the password to NULL and break out of the loop. If none of these things are true, the character is concatenated to $password. When you exit the loop, $password holds the entered password. The following code displays Login: and Password: prompts, and compares the entered password to the corresponding encrypted password stored in /etc/passwd. This requires that the system not use shadow passwords.
20.5.4. See AlsoDocumentation on readline( ) at http://www.php.net/readline, chr( ) at http://www.php.net/chr, on w32api_register_function( ) at http://www.php.net/w32api-register-function, and on _getch( ) at http://msdn.microsoft.com/library/en-us/vccore98/HTML/_crt_ _getch.2c_._getche.asp; on Unix, see your system's stty(1) manpage.
Copyright © 2003 O'Reilly & Associates. All rights reserved. |
|