How to create a silent [password] prompt in PHP

August 28, 2010

I’m creating a script that needs to ask for the MySQL root password and want to do a classic password prompt that doesn’t output the characters. I found this handy script that takes care of it.

The basic premise of the script is to detect windows. If found, use vbscript to create a popup InputBox. Otherwise, good ol’ linux allows you to suppress output:

/usr/bin/env bash -c 'read -s -p "Enter Password: " mypassword && echo $mypassword'

Here’s the whole script:

function prompt_silent($prompt = "Enter Password: ") {
  if (preg_match('/^win/i', PHP_OS)) {
    $vbscript = sys_get_temp_dir() . 'prompt_password.vbs';
      $vbscript, 'wscript.echo(InputBox("'
      . addslashes($prompt)
      . '", "", "password here"))');
    $command = "cscript //nologo " . escapeshellarg($vbscript);
    $password = rtrim(shell_exec($command));
    return $password;
  } else {
    $command = "/usr/bin/env bash -c 'echo OK'";
    if (rtrim(shell_exec($command)) !== 'OK') {
      trigger_error("Can't invoke bash");
    $command = "/usr/bin/env bash -c 'read -s -p \""
      . addslashes($prompt)
      . "\" mypassword && echo \$mypassword'";
    $password = rtrim(shell_exec($command));
    echo "\n";
    return $password;

Stay in Touch!

Subscribe to our newsletter.

Solutions Architecture

browse through our blog articles

Blog Archive