Is it really not possible to write a php cli password prompt that hides the password in windows?

依然范特西╮ 提交于 2019-12-19 03:26:13

问题


I have spent several hours trying to find a means of writing a cross platform password prompt in php that hides the password that is input by the user. While this is easily accomplished in Unix environments through the use of stty -echo, I have tried various means of passthru() and system() calls to make windows do the same thing to no avail.

I have tried:

passthru('set /p pass=Password: ');
system('echo %pass% > out.txt');
$pass = file_get_contents('out.txt', 'r');

This seems to hang on the passthru('set /p pass=Password: '); line without allowing me to input any text and must be killed with a Ctrl-c.

I have also tried various methods of fgetc and fgets and printing backspace characters to hide the input since this works in other languages. However, PHP does not appear to be able to interact with text prior to a carriage return.

I would really like to find a way to make this work, is this an impossible task or is this something that can be done?

Note that I am aware that I could wrap the php script in a batch file and pass the password as a command line argument, but that doesn't work for me in this case.


回答1:


Here's a Windows solution, using the COM extension for PHP. I tested this on Windows XP with PHP 5.2.6.

<?php

$pwObj = new Com('ScriptPW.Password');

print "Password: ";
$passwd = $pwObj->getPassword();

echo "Your password is $passwd\n";

?>



回答2:


There doesn't seem to be an IOCTL or STTY extension for PHP. I found the following trick here:

<?php
echo 'Password: ';
$pwd = preg_replace('/\r?\n$/', '', `stty -echo; head -n1 ; stty echo`);
echo "\n";
echo "Your password was: {$pwd}.\n";
?>



回答3:


I think you cannot do that in PHP with the standard library but you can do better :

Catch the first letter, then display a *. Catch the second one, then display two *...

Ergonomically, this is handy because the user can see what he have entered. Security is not at risk because if somebody can see the password one letter by one letter, he can see the guy typing it on the keyboard anyway. But it still prevent somebody from seeing it by accident in one time.



来源:https://stackoverflow.com/questions/297850/is-it-really-not-possible-to-write-a-php-cli-password-prompt-that-hides-the-pass

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!