Friday, June 7, 2013

Command line password prompt in PHP

These days I’ve been writing a quick command line script in PHP, and at some point I needed the user to type username and password to authenticate in some remote account. The standard way to prompt for a password in Linux is to hide the characters as the person goes typing, and I wanted that feeling on the script.

I assembled some code from here and here and I wrote a small function which prompts for username and password and returns an stdClass, which I share here:
function PromptUsrPwd()
{
	fwrite(STDOUT, 'Enter user name: ');
	$usr = trim(fgets(STDIN));
	$command = "/usr/bin/env bash -c 'echo OK'";
	if(rtrim(shell_exec($command)) !== 'OK') {
		die("Can't invoke bash.\n");
		return null;
	}
	$command = "/usr/bin/env bash -c 'read -s -p \"".
		addslashes("Password for $usr:").
		"\" mypassword && echo \$mypassword'";
	$pwd = rtrim(shell_exec($command));
	echo "\n";
	return (object)array('usr' => $usr, 'pwd' => $pwd);
}
This is an usage example. Run it on command line to see it in action:
$credentials = PromptUsrPwd();
echo 'Your name is '.$credentials->usr."\n";
echo 'Your password is '.$credentials->pwd."\n";