我正在编写一个命令行工具来帮助我的网络应用程序.它需要密码才能连接到服务.我希望脚本显示密码提示,所以我不必将其作为命令行参数传递.
这很容易,但我希望它不会在键入屏幕时回显密码.我怎么能用PHP做到这一点?
在纯PHP(没有system('stty'))和用字符替换字符的情况下的加分点*.
编辑:
该脚本将在类似unix的系统(linux或mac)上运行.该脚本是用PHP编写的,很可能就是这样.
此外,为了记录,stty这样做的方式是:
echo "Password: ";
system('stty -echo');
$password = trim(fgets(STDIN));
system('stty echo');
// add a new line since the users CR didn't echo
echo "\n";
Run Code Online (Sandbox Code Playgroud)
我宁愿不system()接听电话.
小智 39
在sitepoint上找到.
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;
}
}
Run Code Online (Sandbox Code Playgroud)
根据您的环境(即不在Windows上),您可以使用ncurses库(特别是ncurses_noecho()函数来停止键盘回显,并使用ncurses_getch()来读取输入)以获取密码而不在屏幕上显示密码.
您可以使用我的hiddeninput.exe文件获取真正的隐藏输入,而不会在屏幕上的任何位置泄露信息.
<?php
echo 'Enter password: ';
$password = exec('hiddeninput.exe');
echo PHP_EOL;
echo 'Password was: ' . $password . PHP_EOL;
Run Code Online (Sandbox Code Playgroud)
如果删除最后一个回显,则密码永远不会显示,但您可以使用该密码进行验证.
小智 5
以下方法适用于 Linux CLI,但不适用于 Windows CLI 或 Apache。它也只适用于标准 Ascii 表中的字符(尽管使它与扩展字符集兼容并不需要太多)。
我已经放入了一些代码来防止复制和粘贴密码。如果删除了两个注释之间的位,则可以注入/粘贴密码。
我希望这可以帮助别人。
<?php
echo("Password: ");
$strPassword=getObscuredText();
echo("\n");
echo("You entered: ".$strPassword."\n");
function getObscuredText($strMaskChar='*')
{
if(!is_string($strMaskChar) || $strMaskChar=='')
{
$strMaskChar='*';
}
$strMaskChar=substr($strMaskChar,0,1);
readline_callback_handler_install('', function(){});
$strObscured='';
while(true)
{
$strChar = stream_get_contents(STDIN, 1);
$intCount=0;
// Protect against copy and paste passwords
// Comment \/\/\/ to remove password injection protection
$arrRead = array(STDIN);
$arrWrite = NULL;
$arrExcept = NULL;
while (stream_select($arrRead, $arrWrite, $arrExcept, 0,0) && in_array(STDIN, $arrRead))
{
stream_get_contents(STDIN, 1);
$intCount++;
}
// /\/\/\
// End of protection against copy and paste passwords
if($strChar===chr(10))
{
break;
}
if ($intCount===0)
{
if(ord($strChar)===127)
{
if(strlen($strObscured)>0)
{
$strObscured=substr($strObscured,0,strlen($strObscured)-1);
echo(chr(27).chr(91)."D"." ".chr(27).chr(91)."D");
}
}
elseif ($strChar>=' ')
{
$strObscured.=$strChar;
echo($strMaskChar);
//echo(ord($strChar));
}
}
}
readline_callback_handler_remove();
return($strObscured);
}
?>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
39273 次 |
| 最近记录: |