DEV Community

loading...

Reading Passwords from STDIN in PHP

mykeels profile image The Smith! πŸ›  ・1 min read

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

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;
}

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

Discussion (1)

pic
Editor guide
Collapse
mykeels profile image
The Smith! πŸ›  Author

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!