shell - php的cli如何实现读取用户输入,但隐藏这段字符输出
程序员文章站
2023-12-26 22:47:45
...
简单来说就是比如大家用ssh登陆时,一般要求输入密码,然后当你输入时你的输入是被隐藏的,但是后端实际上获取到了你的输入,这是怎么做到的呢?
回复内容:
简单来说就是比如大家用ssh登陆时,一般要求输入密码,然后当你输入时你的输入是被隐藏的,但是后端实际上获取到了你的输入,这是怎么做到的呢?
function prompt_silent($prompt = "Enter Password:") {
if (preg_match('/^win/i', PHP_OS)) {
$vbscript = sys_get_temp_dir() . 'prompt_password.vbs';
file_put_contents(
$vbscript, 'wscript.echo(InputBox("'
. addslashes($prompt)
. '", "", "password here"))');
$command = "cscript //nologo " . escapeshellarg($vbscript);
$password = rtrim(shell_exec($command));
unlink($vbscript);
return $password;
} else {
$command = "/usr/bin/env bash -c 'echo OK'";
if (rtrim(shell_exec($command)) !== 'OK') {
trigger_error("Can't invoke bash");
return;
}
$command = "/usr/bin/env bash -c 'read -s -p \""
. addslashes($prompt)
. "\" mypassword && echo \$mypassword'";
$password = rtrim(shell_exec($command));
echo "\n";
return $password;
}
}
echo prompt_silent();
参考:http://www.sitepoint.com/interactive-cli-password-prompt-in-php/