When to start a session? - php

I have a system that requires the user to login (or register) for an account before they are able to access their Member 'dashboard'.
My question is... at what point so I session_start()? On the login page and the register page? or after the user has successfully authenticated?
Thanks.

You need to include session_start() on every page where you want the session data to be accessible. And it needs to be called before any other output has been done.

As Helge Helwig said,
you need to add session_start() in the top of every page.
However, to make this easier, you can create a PHP document, where
you store all vital code like this, and call it; say init.php.
Then you can include 'init.php' at the top of every page, which would
clean up the code a bit.

Start a session on the page(s) that need to access session data. As part of a successful login, you should also call session_regenerate_id to prevent session fixation.

you can start session once user is authenticated.
after that you can user related information in S_SESSION and access this info from anywhere.

You should start session after verifying user's information, and than you can set user's uid to session variable. which could be useful afterwards in loading user's personal information like profile,preferences etc.
on register page i think you do not need to start session.
Regards

Your session_start() will be called on each and every page that is secure and that is accessed after authentication. You will put the values in session both in login and register pages as they authenticate user. But once the user is verified, now you have to put this function on all pages which needs authentication of the user.

Related

Is it good to wipe $_SESSION before using it?

I am still new in session
Is it good to wipe $_SESSION before using it?
example:
$_SESSION = array();
$_SESSION['id'] = 1;
$_SESSION['name'] = 'Someone';
I am asking opinion from you guys.
Because I don't have many experience in session.
In my awkward logic,
Maybe I will forgot to logout from admin session
and login to member session
So maybe some $_SESSION value from admin will still in $_SESSION array
Additional:
1. I was admin user and not logout yet from admin page.
2. Now I go from admin page to member login page
What should I do here?
Kick admin to the admin page because he is not member?
Nope. In fact, its really bad and your example code will render your sessions useless.
When you call session_start() you are either given an empty $_SESSION or you get back the data you saved to $_SESSION on a previous page load. For more information on sessions check out the PHP docs:
http://php.net/manual/en/book.session.php
http://php.net/manual/en/function.session-start.php
About logging in and out: Your logout process has to destroy whatever session data identifies the user (probably their ID). Typically this is done by using unset, i.e. unset($_SESSION['user_id']).
I can't imagine any other way to log out a user, maybe if you provided more information I could give you a better answer about this.
Regarding your addition it looks like your authentication system could use some work. You shouldn't be able to get to a login page when you are already logged in (even as admin, since its just another user with higher privileges, right?). If you manually type in the login url after you're logged in, then it should redirect you to the homepage.
Here's Fantastic write-up on this topic, I shoulda done some research! Thanks #HamZa
The definitive guide to form-based website authentication
And here's my super basic pseudo code auth process:
Does current page require authentication
Yes:
Is the user logged in?
Yes:
Does the user have the correct privilages to view the page?
Yes:
AUTHENTICATED! Show page
No:
Print a message that says something like, "You're in the wrong place amigo"
No:
Redirect to login
No:
Show the page

converging multiple admin login scripts into one

I have a few scripts all linked to the same SQL database, but each one has its own admin.php
I have created links to the other admin.php(s) in the one I would consider the main admin panel.
as it is the same user name and ID how can I get the links to fill and submit the login details so I only have to login on the first admin panel and not each time a click a link to a new one
any help appreciated
You probably want to store some kind of authentication information in session data. Each time you access a script, it will check the session variables for some kind of security token. If it's there, it can use that to determine who has logged-in.
At the top of each PHP script (before you've output any HTML), include a call to session_start(). This will enable session information. You can then read/write elements in the $_SESSION superglobal array.
If you want the browser to remember the login for subsequent visits, you could also use cookie data. Just be aware that cookies are not particularly secure, so don't store usernames and passwords in them directly. Use some a unique encrypted/hashed token instead.

PHP + Logout Member when Session Expires

I've a site where people login and a SESSION is created.
I have noticed that if you leave the site for long enough (not sure exact time frame) the session ends but the members is still in the site. They can still click and navigate around and I believe this has resulted in some meaningless data in the DB as SESSION variables like userID don't exist.
I was looking for advice around logging users out when the SESSION ends.
I have looked at code like this - any better ideas?
<?php if(!isset($_SESSION[]) {header(loginpage.php);}?>
Is there a better way to write the above code?
Where should this code be placed? Just on the navigation menu or really on any place a user can click?
Finally is there a way to understand when the SESSION naturally expires - is there a SESSION variable I can print to screen to see the timeleft etc?
thanks
You need to validate the session, you already headed into that direction with your code, but it's not enough:
<?php if(!isset($_SESSION[]) {header(loginpage.php);}?>
It's not enough because $_SESSION[] exists automatically after the session is started (the session mechanism in PHP, see session_start).
Instead, if you have saved the userID inside the session, check that one:
isset($_SESSION['userID'])
If the session really expired, it should not be set.
I agree with the above answer. I would say it depends on how your application is architected to say where this belongs. before there is any output to the screen I am assuming your calling session_start, then immediately check for a session variable such as userID that gets set after a user logs in. if it's not set redirect setting a header for location to your login page. you could also write some js that checks the session cookie for a value at a specified interval(I believe, it's been a while so test it out), then when the variable isn't present you can redirect to the login page. a third way would be for the js code to make an XHR call to a php script to check out the session for you.

Restricting sessions to only 1 instance of a user login

i have a user login system which works off of sessions such that when the user logs in a session variable of user is populated with his/her username, then each page she loads checks this session, if it is not populated then the page is redirected to the login page. apon logout the session is destroyed.
But this still allows a user to open 2 different browsers at the same time and login. I want to stop this, such that if a user logs in and then trys to login using a different browser or pc, they get an error saying the user is already logged in.
So my first thought was to use a data base write, but then how do i know to unset that value if the browser is closed?
all my pages are php, and i use ajax and php scripts to update dynamic content.
So whats the best way to go about this?
they get an error saying the user is already logged in.
That's wrong approach, causing terrible user's experience.
Make it opposite: let that latter in, but make previous one logged out.
You only need to store current session ID in the user's table. If it doesn't match - ask for login.
If you find in DB that user is already logged in simply ask if he/she wants to go on and overwrite old session info. Another way may be adding a time-ticket to your database information (e.g. inserting time) and check how long is elapsed since inserted.
Regards
If I have understood your question properly, I think you can make use of cookie. Once user is logged in, you can create a cookie and set an expiry to browser session time. Before fetching data from DB, you need to check for cookie presence.
I would make another session variable that checks the browser type, if it is different call a view method to output what you said

PHP login user logic

I've scrapped all the tutorials that have never worked for one reason or another, and decided to roll out my own registration/login feature on my own, and to my surprise it actually works!
But what I don't get is how the logic behind keeping somebody logged in works! Like, once they've logged in, do I just $_POST their data to whatever other page they visit and once they're on the new page $_REQUEST that post data from the URL and display a message like: "yeah, you're still logged in"?
I'm a bit confused atm, so I hope this question doesn't confuse you too.
Let us have we have pages like login.php after_login_page1.php after_login_page2.php
You can follow these simple steps
Set $_SESSION['id'] = $userid //userid from db in login.php
always have session_start() in the successive pages like after_login_page1.php, after_login_page2.php
Check if(! isset($_SESSION['id'])){
header("Location: login.php");
}
at the logout.php page give $_SESSION['id']=''; and do a session_destroy()
The easiest imo is to use a session.
Basically this is PHP automatically setting a cookie (or adding a piece to the url, depending your configuration) on the user system and automatically loading it on each pageview. You can then add data to the session and as long as the cookie didn't expire (or was deleted) and/or you don't destroy the session, you will have that data at your disposal on each pageview the user does.
Take a look here for a small intro to sessions: http://www.htmlgoodies.com/beyond/php/article.php/3472581/PHP-Tutorial-Sessions.htm
Once they have logged in you generally have two options. Store their details or an authentication token (something that will help the PHP on the server know who is who) in a session or store it in a cookie. Both have their perks, but you will need to choose the one that works for you.
If you store data in a session, the user cannot access what you have stored, only your code can. This is helpful if you want to store say, their id or username. You can trust that it would always be their id and username, because they cannot modify it.
With cookies, the user can access and modify them because they are stored on their local machines. Because of this, you need to be a bit more sneaky and hash the users details, then verify who it is with some server-side logic. It's a little more complex.
A session implementation might look like this:
session_start(); //Make sure you call this at the top of EVERY page
if($passwordsMatch){
$_SESSION['user'] = $_POST['username'];
}
//Now we have access to $_SESSION['user'] on every page.
On another unrelated page:
session_start();
print "Welcome, ".$_SESSION['user'];
Easiest way is to "keep users logged in" is to use PHP sessions. When you run session_start();, PHP sets cookie with SESSION_ID in users browser so it can identify this user. After that, you can set any data in $_SESSION array which will be saved in session between page requests.

Categories