Search code examples
javascriptphpcookies

Is this possible to keep login credentials alive using PHP?


If anyone logs into Google, Facebook, Amazon, or Stack Overflow the login credentials of that person will remain alive till log out. I want to ask how can I keep the login credentials of my user alive on his/her computer till logs out using PHP or Javascript.

It is possible to use PHP or Javascript if not what can I do or what technology should I use?

Should I use the Cookie function and set the expiration time till my domain expires using mktime function?


Solution

  • The login procedure is not as the same as you think. Facebook, google and other websites are not keeping login credentials until user logs out.

    There are two major ways that you can use to authenticate users to your website.

    • OAuth is one way where users have to provide there username and password each and every time when they access the website. To do that you have store username and password in Cookies or somewhere, then you can pass them with every request

    if you need to store login credentials as cookies you can do it like this,

    document.cookie = 'username=username; expires=Sun, 1 Jan 2023 00:00:00 UTC; path=/'

    BUT DON'T DO THIS!

    Storing Login credentials is high security risk.

    1. OAuth2 is the most secure way. Lets assume that one user is trying to login to your website for the first time. When he enters username and password your web server validates them and if they are correct, server will send a Token back. Token is a Long String which is harder to be guessed or brute forced.

    Then you can store that token in cookies

    document.cookie = 'token=tokenhere; expires=Sun, 1 Jan 2023 00:00:00 UTC; path=/'

    and pass the token with each and every request. So the server can validate user requests without login credentials.