Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cookies/Sessions login system

When a user logins I get him/her's ID and save it in a session var. What I wonder is, is this the way to go? Or should I use cookies? so it automatically login and so on.

session_start();


ifcorrectlogin {
$_SESSION['id'] = mysql_result($loginQuery, 0, 'user_id');
}

how do you authenticate your users?

//Newbie

like image 766
Erkka Avatar asked Dec 25 '09 23:12

Erkka


People also ask

Should I use cookie or session for login?

session login is always preferred, if you specifically do not need any cookie variables to set for your webpage. Sessions use either a cookie to pass the session id between pages or add it in the querystring.

How are cookies used for login?

Websites typically use cookies to ensure that users are recognized when they move between pages, so they don't get asked to log in again every time. Websites also use cookies to remember information users have entered.

What is cookie and sessions?

Cookies are client-side files on a local computer that hold user information. Sessions are server-side files that contain user data. Cookies end on the lifetime set by the user. When the user quits the browser or logs out of the programmed, the session is over. It can only store a certain amount of info.

How does a login session work?

Websites use a session ID to respond to user interactions during a web session. To track sessions, a web session ID is stored in a visitor's browser. This session ID is passed along with any HTTP requests that the visitor makes while on the site (e.g., clicking a link).


1 Answers

Yes, this is the way to go. The session itself is already backed by a cookie to remove you any programming efforts around that. The session (actually, the cookie) will live as long as the user has the browser instance open or until the session times out at the server side because the user didn't visit the site for a certain time (usually around 30 minutes).

On login, just put the obtained User in the $_SESSION. On every request on the restricted pages you just check if the logged-in User is available in the $_SESSION and handle the request accordingly, i.e. continue with it or redirect to a login or error page. On logout, just remove the User from the $_SESSION.

If you want to add a Remember me on this computer option, then you'll need to add another cookie yourself which lives longer than the session. You only need to ensure that you generate a long, unique and hard-to-guess value for the cookie, otherwise it's too easy to hack. Look how PHP did it by checking the cookie with the name phpsessionid in your webbrowser.

like image 183
BalusC Avatar answered Oct 18 '22 03:10

BalusC