开发者

Managing login in php

Obvio开发者_运维百科usly I have my own opinion and way of doing this, but I would be curious to see if there were any better ways.

How do you manage logins, i.e. check if user is logged in with valid login before serving members only content.


  • Make use of $_SESSIONs
  • Start every single page with session_start();
  • Check for a custom $_SESSION variable for member content ($_SESSION['username'])
  • If your variable isn't presented, display a login form
  • Upon successful login set $_SESSION['username'] to currently logged in user's nickname

Note: This is a brief description of managing logins, there are a lot of things isn't described here. You should avoid different security holes like sql injection, session-hijacking, etc)


Once upon a time, I made a Session class, which was instantiated in a common include file. Rather than using session_* and $_SESSION, it used a cookie with a client-side SID (I think it was a SHA-256 hash with salt and a few iterations). On the server, the client-side SID went into another hashing function a few times to get the server-side SID, which was the primary key in a remote MySQL database.

Why? Because the site was on shared hosting, but the sessions needed to be secure as the database held details of people under 18. PHP by default uses /tmp as the place to store session data as serialised files, meaning that anyone with access to /tmp (i.e. any other customer on the same host) could access the serialised form of session data and possibly use it to appear authenticated.

It was a good way for me to learn about session handling, HTTP headers etc. and it felt much nicer to work with than the standard PHP way.


I check the authentication cookie.


I would not manage it myself anymore. There are just too much things that can go WRONG. Instead I would use OpenID just like stackoverflow.com does.


I don't know if it's the best way to do it but i'm used to create a user class and create the object when i create a new session. I store this object into the session and i'm used to link the session var to an enviroment var, just to avoid to deal with the $_SESSION array. In this way you can keep the login method and the login status inside the object itself, together with all the information related to the user (name, surname, access level, etc)

something like that:

include('user.class.php');
session_start();

if(!isset($_SESSION['user']))
{
   $_SESSION['user'] = new User();
}

$USER = &$_SESSION['user'];


Not a new article, but this system is amazingly good. There may have been some more recent updates to the original article.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜