Blog Post RSS ?

Blogs » PHP » Interactive CLI password prompt in PHP
 

Interactive CLI password prompt in PHP

by Troels Knak-Nielsen

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;
  }
}
Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Ping.fm
  • Twitthis

Related posts:

  1. How to Use PHP Namespaces, Part 2: Importing, Aliases, and Name Resolution In the second part of Craig's PHP namespaces series, he...
  2. How to Use PHP Namespaces, Part 1: The Basics In the first part of a series of articles, Craig...
  3. How to Use PHP Namespaces, Part 3: Keywords and Autoloading In the final part of his series explaining PHP namespaces,...
  4. How to Install MySQL Installing MySQL is easier than you think. Craig provides a...
  5. How to Install PHP 5.3 on Windows PHP 5.3 is the most significant update since version 5.0....

This post has 11 responses so far

Sponsored Links

SitePoint Marketplace

Buy and sell Websites, templates, domain names, hosting, graphics and more.

Follow SitePoint on...