DEV Community

Backlog Slayer
Backlog Slayer

Posted on

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. 😍

Top comments (2)

Collapse
 
mykeels profile image
Backlog Slayer

A friend just pointed out that Laravel's artisan commands already come with the $this->secret($prompt) method, to retrieve passwords from STDIN. 😂

This article aged real fast!

Collapse
 
programster_uk profile image
Programster

Yes but this is still useful as not all PHP applications are written using Laravel, just as not all things that use Javascript use jQuery.
Thanks.