When to create sessions in PHP (somewhat specific situation)? - php

I have a large number of pages, each of which use a common header/footer. My wish is to keep the header and footer standard regardless of which page the user is on.
To access administration functions, the user presses an administration link at the bottom of the header. I would like this administrative login link to change to a log-out link after the user is logged in.
If I use session_start() in the header, then every page is going to have a session. I was told (I'm not sure if this is true or not) that it is bad practice to always have a session open.
Making matters worse in this regard, many of my pages use sessions (specifically all the administrative ones), and if you try and call start_session() after a header is sent (which obviously happens because my common header is parsed prior to the page content script sections being run, then it is an error.
To this point, I had been calling start_session() before the require line for the header on pages that would need sessions - but if the header now starts the session then this becomes an error.
If I need to know when an administrator is logged in within the common header code, how do I handle my session creation? Am I looking at this wrong?

I was told that it is bad practice to always have a session open.
yes. start your sessions only if you really need them.
otherwise it will make your site unnecessary slow, forbid browser from caching your pages when possible and such.
although you can't serve registered users without sessions, all other requests to the site (especailly from search engine bots) require no session support and there is no reason to start it.
how do I handle my session creation?
thre is a very simple solution.
call session_start() only on 2 occasions:
when user actully logs in.
when your script recieved a session identifier (means there is an active session running)
So, just add session_start() call right after the code checking user's password and modify all other calls this way
if (isset($_REQUEST[session_name()])) session_start();

There's the simple way of looking at sessions. If the page a user is on requires sessions, use sessions. Even if the page a user is on does not require sessions, if that page is one that a user reaches after a session has started, and it is reasonable to assume that a user will go from that page to another page that requires sessions, maintain the session. Don't keep starting and stopping your sessions. Just, as a rule of thumb, don't start the sessions until you need them and end them when you can be very confident that a user will not be needing them again during their visit.

In general, you are reinventing the wheel. Not using a CMS for these tasks is a waste of time and effort. In specifics, ob_start() is your friend.

I was told (I'm not sure if this is true or not) that it is bad practice to always have a session open.
That is hugely false. StackOverflow, Google, Facebook, etc. would all cease to function without an always-on session.

Related

Where is the correct place to call session_start()?

There seem to be two principle ways of setting out a login system with PHP from the code I have studied as a beginner. I would like to know which is the "better" way to do it.
The first way calls session_start() in the header of every page, regardless of whether the user is logged in or not. The login script when called adds variables via $_SESSION. If the variables match the Users table then the user is logged in and gains access to the login area.
The second way first calls session_start() in the login script, and then in every further page within the user area.
Given that session_start() needs to be called to create or resume sessions, is best practice simply to put it in the header and forget about it?
OR
Should session_start() be called for the first time in the login script?
What are the implications of this decision?
The first way calls session_start() in the header of every page, regardless of whether the user is logged in or not.
This is ideally the best option for a number of reasons.
Maybe additional functionality can be added for security (or other reasons) from the very start. For example, maybe you could have some blocked IP addresses which you do not want to access your website, or you could use the session for gaining statistics.
So maybe you want to see where a person was redirected from to get to a certain page, even when they are not logged in.
Overall it helps to develop easier session management for security reasons and develop statistic functions.

PHP how to manage multiple session in same browser using cookies?

I'm new to PHP, I read other articles without finding the answer I'm looking for, but still don't know if what I want to do makes sense or not.
I'm using PHP 7.
My user authentication page, checks credentials and then executes session_start(), creating the session server-side and a cookie client-side in the browser.
Each other page of the web application then calls session_start() to resume session information, in this case checking the cookie. Everything works fine so far... at least when I have a single login.
I'd like to be able to have more than one user SIMULTANEOUSLY logged in the same browser (on another tab for example.) using cookie. I don't want to append the session ID to the URL.
I managed to create different session on the server-side using session_id() before session_start() in the authentication page based on username, but the problem is on the client side.
The first successful login (session_start()) creates a cookie and the second login updates the same cookie corrupting the previously created session.
Therefore when it comes to resume the session, session_start() will resume only the last session, mixing the data fetched from DB based on session info.
Is there a way to make session_start() create a cookie for each login and make PHP resume the correct session using cookies?
Any ideas?
FURTHER DETAILS:
I'm updating a legacy app trying to fix some security issue. The need for multiple sessions comes from administrative purposeses where admins access the same site. The reason why it's needed a separation of session is that depending of the session info, the data are fetched from a different database. Therefore, a regular usage would only need one session per user, but the administrator he needs to make multiple logins viewing different data depending on that login.
The default PHP behaviour is to handle sessions using cookies.
..and the default behaviour for browsers is to "reuse" the same set of cookies if you revisit an URL in another tab.. So, like mentioned below:
The simple way probably is to start another browser. Not the same browser but like firefox and chrome, if you have multiple browsers installed.
Another way would be to install a browser plugin, like Sessionbox for Chrome or Multifox for Firefox.
Edit, for clarity: I can think of two cases when multiple sessions would be used:
During development. Depends on the application, but an obvious case would be testing communication between two users.
After deployment. Though I've never seen a site that required multiple logins for the same user account.
This is my frame of reference. Based on this I assumed the question was for development. I'm not suggesting that the site should require installing extra packages. Flash would be about the only one that's ever gotten away with that..
You can use the same session but change the variable names that you are looking for:
if ( $_SERVER['REQUEST_URI'] == '/admin/' ):
$session_name = 'session1';
else:
$session_name = 'session2';
endif;
session_start( $session_name );

session_start in php in index.php

On my index.php, I have a login form. The form has a method of POST and its action is sent to a authentication file i.e action="authenticate.php". In this authentication file I check to make sure the user exists, I start a session, and then I redirect back to index.php.
Because I want the index.php content to change, for example, there will be no login form but the user account information, I also place a session_start() at the top of my index.php...
The problem occurs when a user visits my page for the first time. Because I placed a session_start() at the beginning of my index.php, if the user leaves and decides not to log in, then I'm stuck with an empty session file which takes up space on the server.
Is this bad practice? Is there another method that I should use? I hope this makes sense.
PHP cleans up sessions that are not in use anymore.
The usual configuration is to only run cleanups on a percentage of requests, and then to clean up session files that haven't been used in the last 30 minutes. Note that this leaves an opportunity for sessions to live longer on sites that rarely have any requests, so it is best practice to record the enforced logout time inside the session itself if there is a need to log the user out when being inactive after for example 15 minutes.
Also note that on a badly configured shared hosting you might gain access to other sites session files and vice versa, which might also affect cleanup of session files if other sites have a different, shorter timed configuration.
But all in all PHP takes care of the sessions itself pretty well.

How to manage session effectively when you have a very complicated database

I have one user portal account. I'm logging into it with two different usernames in two different tabs.
When I do a hard refresh (ctl+f5) in both tabs of the same user account, it opens in both tabs. That can be any username from those two. What can I do to fix this problem?
Session's mechanism uses COOKIEs. COOKIEs are shared between tabs.
If you what to login with one browser session by two differnet users you can disable storing session id in cookie: PHP session without cookies.
Also you can use feature of browsers. FireFox's Private browsing for example.
PHP's sessions. Basic usage.
PHP's sessions. Passing the Session ID.
You cant login on same website on same browser with two different user. Better you use two different browsers.
One option would be to avoid session cookies. Add the PHPSESSID variable to the query string, or have it in the path and use URL rewriting or PATH_INFO to translate /x/y.php/925235a... etc to /x/y.php?PHPSESSID=925235a.... You can actually tell PHP to do the first for you.
Note, in order for this to work, you'll need to say something like
ini_set('session.use_cookies', false);
or the like, in your script before calling session_start(). Then PHP won't send session cookies; in most cases it will just transparently rewrite URLs in your page to include the session ID, so you get the first option for free.
The biggest drawback to this approach is that it makes your users vulnerable to an attack called "session fixation". If i hand you a URL that already has a session ID, and you click it and log in to the site, you've logged in my session for me and i can now visit the site as you. One way around that is to switch to a new session when someone logs in...but if your app is a shopping cart, it can be annoying making people log in to buy something.
Second biggest: If a user follows a link that doesn't have a session ID, PHP won't recognize them. (The user can use the "Back" button to get back to a point where they have a session ID, but that sucks usabilitywise.) You have to ensure that the session ID appears in every link or URL. Fortunately, PHP will rewrite most of them for you, but any links you generate with JS and such, you'll have to do yourself.

PHP Sessions not transferring after forms and redirects

I have secured pages that all check for a set session variable to determine logged in users, pretty standard stuff. Where I run into problems is when I submit form information to a backend page that will process that data and then redirect to a success/failure confirmation page. In that time the session gets lost, at least the session with the variable. The session is still around because I can manually navigate to a secured page after and it works. Just auto redirects from a backend page to a secured page or a link on one of the unsecured pages after a redirect from the backend will fail. It may or may not be related, but after visiting multiple secured pages or doing one of the operations that use the problematic backend pages, there are two session cookies on my computer from the domain-- one registered to domain.com and the other to www.domain.com. At the end of my wits about this, thanks.
I see two problems here, but they're related.
The first is that you seem to be bouncing between secured (https://) and un-secured (http://) pages. Cookies aren't supposed to be shared between those, so that's why your session appears to break (PHP sets a cookie with the session ID).
The other is closely related and that is sharing between domain.com and www.domain.com. Cookies can share in one direction, but not the other. Don't worry about which: just pick one hostname and stick with it. Then check that you're setting the session's cookie domain to the correct one.
You must call session_start() from your PHP page before you output anything, preferably at the start of the page.
If the session has been already created, it will resume it for that page.
http://php.net/manual/en/function.session-start.php

Categories