Programming
Article
By Troels Knak-Nielsen

Interactive CLI password prompt in PHP

By Troels Knak-Nielsen
Last chance to win! You'll get a... FREE 6-Month Subscription to SitePoint Premium Plus you'll go in the draw to WIN a new Macbook SitePoint 2017 Survey Yes, let's Do this It only takes 5 min

Just a quick tip, since I spent a good hour figuring this out recently. PHP has no native way of doing an interactive password prompt, when running as CLI. You can however use bash for the task. Of course this means that it won’t work on Windows, but you should be fine on most anything else. Edit: Using Windows Scripting Host, it’s possible to pop a prompt up for the user to type in. I’ve extended the example to use this technique for Windows based systems.


/**
 * Interactively prompts for input without echoing to the terminal.
 * Requires a bash shell or Windows and won't work with
 * safe_mode settings (Uses `shell_exec`)
 */
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;
  }
}
Login or Create Account to Comment
Login Create Account
Recommended
Sponsors
Get the most important and interesting stories in tech. Straight to your inbox, daily.Is it good?