Last Updated: February 25, 2016
·
500
· jthayne

Getting user input with optional hide from view

/**
 * Description
 *        This function will request the user's password via the command prompt
 *        Credit to: <http://marc.info/?l=php-internals&m=117442143122154>
 *
 * Arguments
 *        $prompt - string (required). The text for the prompt
 *
 * Examples
 *        $password = getUserInput('Enter password: ');
 *
 * Returns string
 */
function getUserInput($prompt, $hideInput = false)
{
    $displayInput = '';
    if ($hideInput === true) {
        $displayInput = ' -echo';
    }

    $ostty = `stty -g`;
    system('stty' . $displayInput . ' icanon min 1 time 0 2>/dev/null || stty' . $displayInput . ' cbreak');

    echo $prompt . ': ' . ' ';

    // Get rid of newline when reading stdin
    $r = substr(fgets(STDIN), 0, -1);

    // echo PHP_EOL;
    system('stty ' . $ostty);

    if ($hideInput === true) {
        echo PHP_EOL;
    }

    return $r;
}