如何安全地管理连接的用户

I think that I figure dout how to do this:

When my user connect, after checking if he has the good username/password, a session key (a random long string) is created and put inside the DB. The same session_key is put inside the session.

If the user get out of my app without login off, when he comes back, if his session_key match one in the DB, the user is O.K and will connect as the user that have that session_key. If not, the session is closed, the user is rerouted to login. If there's no problem, a new session_key is created (to replace the old one).

I think it would be O.K., except for 2 things:

-How can I make the session_key disappear from DB after a certain time? I guess I should execute some code on the server, but how can I execute code on the server if nobody is using my app for a certain moment?

-If it's just the session_key, is it alright to use the cookie insted?

-Is it O.K. to just check if there's a session_key in the DB that correspond to the session_key in the session, or should I use something else to be sure? I will generate a random long string and crypt it the same way I do with password, so i think it will be secured enough and that it wouldn't be likely that the session_key be identical.

-insteed of using the username to get data from the DB, would it be O.K. to use the session_key (getStuffBySessionKey())?

What if my user access the cookie and change the username?

There's no need to store the username in the cookie. The cookie should only have the session key info. You'll get the username from that via db query when the user attempts to login. If the user changes the session key value in their cookie, then it will no longer match an active session in the database, and they will have to log back in. It's essentially the same as clearing the cookie.

In addition to the username and the session_key, I will put the user privileges in the cookie. I will need it to know if the user is admin, creator or visitor.

These should be stored in the database as well, not in a cookie.

Is there an other way to check if the user didn't try to change anything WHILE he still is on the app?

Nope, you should be checking for a valid, active session on every request from the user. If there's no session cookie, or if the cookie doesn't match a valid session, redirect them to the login page.

As others have pointed out, you'd be wise to use PHP's built-in sessions for all this.