Getting a password hidden from STDIN with PHP-CLI
Friday, August 22, 2008
Today a friend asked me if it is possible to get a password with PHP-CLI, without the usual output of STDIN. I was kinda sure that there must be some way, and so I tried a bit around. I quickly found out, that there was no native PHP way, just a halfy working one with non-blocking STDIN, but not really what I expected. So I searched a bit on the internet, and found a way, how to catch single characters on the shell. With this knowledge I was able to create a tiny function, which can both output nothing while entering the password as well as character replacing stars. For those of you who are interested in this piece of code, here it is:Note: This works on *nix systems only!
<?php/*** Get a password from the shell.** This function works on *nix systems only and requires shell_exec and stty.** @param boolean $stars Wether or not to output stars for given characters* @return string*/function getPassword($stars = false){// Get current style$oldStyle = shell_exec('stty -g');if ($stars === false) {shell_exec('stty -echo');$password = rtrim(fgets(STDIN), "\n");} else {shell_exec('stty -icanon -echo min 1 time 0');$password = '';while (true) {$char = fgetc(STDIN);if ($char === "\n") {break;} else if (ord($char) === 127) {if (strlen($password) > 0) {fwrite(STDOUT, "\x08 \x08");$password = substr($password, 0, -1);}} else {fwrite(STDOUT, "*");$password .= $char;}}}// Reset old styleshell_exec('stty ' . $oldStyle);// Return the passwordreturn $password;}// Get the passwordfwrite(STDOUT, "Password: ");$password = getPassword(true);// Output the passwordecho "Your password: " . $password . "\n";
Comments to this article
Leave a comment
Please note that your email address will not be shown, it is only used to fetch your avatar image from gravatar.com and for notifications.


this is great, thank you very much for the work :-)
i have tons of applications that need this :)
Hey thanks for posting this. Exactly what I was looking for and works great!
thanks a lot !
(I'd like your horde style captcha too :)
Great ! this is very useful. Thanks for sharing your work.
very ugly ..... NOOOO i'm joking
very helpful thanks! :)
Thanx for this! Very nice solution!
THANK YOU! I've searched ~2h a solution for a y/n confirm question in a php-cli application. With your code I can handle every input char without waiting for a newline. Great! :-)
Greets from Vienna, Christian