When a user logged in website, I only save user_id
in SESSION to check it later whether user logged in or not.
if(!empty($_SESSION['user_id'])){
....
Is this enough for security?
The register. php page asks for the desired username, email, and password of the user, and then sends the entered data into the database, once the submit button is clicked. After this, the user is redirected to the index. php page where a welcome message and the username of the logged-in user is displayed.
Check Session ID With session_id() Function Before you can check for a session ID, you need to start a PHP session with session_start() . Afterward, you can call on the session_id() function. This function will return the current session id.
$_SESSION are super global variables which store values in SESSION and can be accessed like arrays. So user_id is just an index of a value in Session not a reserved keyword.
How to Access Values From a Session in PHP? You can access a session variable's value by using the global variable $_SESSION. In the example stated below, you will create another session with a variable that stores your name. session_start();
This would depend entirely on how that variable makes it to the session and how well you're managing session.
One case to always consider when dealing with web-site security and user credentials is the possibility of a user logging on to your site in a public environment and then walking away. How long will he stay logged in? How accessible is the sensitive information when already logged in?
If you have a relatively short session timeout and are making sure that you are managing what makes it into $_SESSION['user_id'] then this is a reasonable approach. It may be better to actually check the VALUE of what is in $_SESSION['user_id'] but that won't be a huge improvement over what you currently have.
The main thing that I would recommend taking into account would be to require login credentials once more if a user ever wants to alter their account's details / access overly sensitive data (you wouldn't want a stranger changing your users' login names would you?). While this may be a bit of a hassle for regular users, it definitely adds a good measure of security to your application.
The value could only be changed if someone has access to the session files.
So usually yes.
But I would rather use isset()
:
function loggedIn()
{
if (isset($_SESSION['user_id']) && is_numeric($_SESSION['user_id']))
return true;
return false;
}
Because if the user id is 0, empty()
will also return true!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With