Reading Passwords from STDIN in PHP

mykeels

Backlog Slayer

Posted on July 4, 2018

Reading Passwords from STDIN in PHP

Hi Everyone,

Recently, I had to create an artisan command that submitted some data on behalf of a user.

I needed it to have access to the user's password to do that.

My first thought was to store the password in an environment variable. I really did not want to do that, and preferred to make the user of the script enter the password every time it was necessary.

[Secure Password Prompt](http://osxdaily.com/2015/02/04/terminal-wont-show-password-when-typed)

How it was done

It was important to ensure that the password was entered securely (invisible too), so I looked into how to and here's what I came up with.

private function getPassword($prompt = "Enter Password:") {
    echo $prompt;

    system('stty -echo');

    $password = trim(fgets(STDIN));

    system('stty echo');

    return $password;
}
Enter fullscreen mode Exit fullscreen mode

How I understand it

The stty command, as I understand it now sets the terminal properties.

  • stty -echo sets the echo property to false, so the terminal will NOT echo the input it receives to the screen, rendering the password invisible

  • fgets(...) retrieves input from a stream interface (STDIN).

  • STDIN is the input stream that fgets reads the input from

  • stty echo restores the echo property to true, so we can now see output on the screen again

I hope you learned something from this, as I did. Happy Coding. 😍

💖 💪 🙅 🚩
mykeels
Backlog Slayer

Posted on July 4, 2018

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related