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.
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 theecho
property to false, so the terminal will NOT echo the input it receives to the screen, rendering the password invisiblefgets(...)
retrieves input from a stream interface (STDIN).STDIN
is the input stream thatfgets
reads the input fromstty echo
restores theecho
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)
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!
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.