Reputation: 344
I have a web app in which after user is logged in, he/she has cookie set for username set by setcookie()
.
Please suggest better approach for security.
Upvotes: 1
Views: 203
Reputation: 920
Use PHP sessions instead of cookies. The session variables are server-side. PHP will automatically handle the session management. You can also overload its functionality if you want more control.
http://php.net/manual/en/intro.session.php
session_start();
$_SESSION['user'] = 'michael'
With PHP-sessions, only a session identifier is stored in the browser cookies. You can store any information in the superglobal variable $_SESSION
, and the browser will not be able to see or tamper with these variables.
For extra safety, you should store the remote address that was used to login, and compare it on each page load. This is to make sure that nobody hijacked the session id and is pretending to be logged in from another location.
session_start();
if (_logging_in__) {
$_SESSION['user'] = 'michael'
$_SESSION['ip'] = $_SERVER['REMOTE_ADDR'];
}
To see if a user is logged in.
session_start();
if (isset($_SESSION['user'])) {
// the user is logged in
if ($_SERVER['REMOTE_ADDR'] != $_SESSION['ip']) {
// the session id was hijacked so log out
session_destroy();
exit;
}
}
Upvotes: 2