I have some jsp pages that I have to transform in php pages. in my jsp I could get the logged user by with this request.getUserPrincipal().getName()
. How do I do that in my php page to get the logged user?
You can have a table called logged_users
that is structured like this:
id | user_id | created
------------------------------------------------------------------------
abc | 1 | 11-12-2014 12:31:51
xyz | 2 | 11-12-2014 08:21:13
id has some unique id
, like a UUID
or a randomly generated string. user_id is the id of the user to be remembered. created is when the record was created (so you can log out the user after X time).
Now, if the user successfully logs in and wants to be remembered, you add a new record with a unique id and his user_id
to logged_users
. You also create a new cookie using setcookie()
that will contain the randomly generated id
you just inserted.
Now, when the user requests the site next time, you see he has the remember cookie stored. You fetch that record, check if its not yet expired and use the user_id
column to log in the appropriate user. This way, you're not storing sensitive information in the cookie.
OR
First, make sure you enable the session variable on all pages that require knowledge of logged-in status by putting this at the beginning of those pages:
session_start();
Next, when the user submits their username and password via the login form, you will typically check their username and password by querying a database containing username and password information, such as MySQL. If the database returns a match, you can then set a session variable to contain that fact. You might also want to include other information:
if (match_found_in_database()) {
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $username; // $username coming from the form, such as $_POST['username']
// something like this is optional, of course
}
Then, on the page that depends on logged-in status, put the following (don't forget the session_start()
):
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) {
echo "Welcome to the member's area, " . $_SESSION['username'] . "!";
} else {
echo "Please log in first to see this page.";
}
Those are the basic components. If you need help with the SQL aspect, there are tutorials-a-plenty around the net.
Hope this helps you.