Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Command Line Password Prompt in PHP

Tags:

php

passwords

I'm writing a command line tool to help my web app. It needs a password to connect to the service. I'd like the script to show a password prompt so I don't have to pass it as a command line argument.

That's easy enough, but I'd like it to not echo the password to the screen as it's typed. How can I do this with PHP?

Bonus points for doing it in pure PHP (no system('stty')) and replacing the characters with *.

EDIT:

The script will run on a unix like system (linux or mac). The script is written in PHP, and will most likely stay like that.

Also, for the record, the stty way of doing it is:

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"; 

I'd prefer to not have the system() calls in there.

like image 330
Gary Richardson Avatar asked Oct 09 '08 15:10

Gary Richardson


2 Answers

Found on 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;   } } 
like image 156
DaveHauenstein Avatar answered Sep 19 '22 08:09

DaveHauenstein


Depending on your environment (i.e., not on Windows), you can use the ncurses library (specifically, the ncurses_noecho() function to stop keyboard echo and ncurses_getch() to read the input) to get the password without displaying it on screen.

like image 29
Randy Avatar answered Sep 19 '22 08:09

Randy