Where is the correct place to call session_start()? - php

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.

Related

Should I use Session variables or the global supervariable

I have a small situation here but I wanted to try and be sure I was approaching this in a correct way.
I have a web application that is used by several shops.
Each shop is authenticated through htaccess and htpasswd in order to connect to the correct database.
This portion works great!
Each shop has multiple employees but each employee uses a separate computer/workstation.
So it goes Shop logs in, gets authenticated, connects to proper database and then loads a login page.
At the login page the user logs into the application using name and password, and they are good to go.
At this point I am loading user information (UserID, Security Level, etc) into the session.
Part of my problem is trash collection as every once in awhile the session variables are getting lost.
Every page has session start as the first thing so I imagine after an hour or so of inactivity the session is getting collected by the trash collector and poof, it is gone.
I am toying with the idea of loading the user information into the $GLOBALS supervariable to avoid losing the session due to inactivity.
Now, I realize that there are ways to delay/stop the trash collector in PHP but it seems to me if I use the global scope it removes the need for extra coding or configuring of PHP.
Am I correct in assuming that as long as each user is on their own machine accessing the site that using the $GLOBALS will only apply to each user?
Think you have a general misconception of session and global variables.
Global variables are the variables which remain common for the whole
application… Their value can be used across the whole application
whereas Session variables are variables which remain common for the
whole application but for one particular user. They also can be used
across the whole application… But they die when a particular user
session ends.
https://stackoverflow.com/a/14848246/1022914
I recommend using sessions though. Check the user details against user data stored in a database. If it passes authentication, create session variables with user data to be used across your pages. This makes thing a whole lot easier
You can use cache . It can help u to keep user logged in always , as facebook .

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 Beginner Security Fear

I'm a tech writer who has done a lot of HTML/CSS but have been thrown into a pressure cooker to rewrite a web app in PHP and have done fairly well, but I'm a bit concerned re the security.
Specifically, the main page is INDEX.PHP, where the user logs in. Once they are logged in, the page rewrites portions of itself and shows menu options not available to users who aren't logged in. About 50% of the users will never need to login since they'll be viewing public documents for which no security is needed. The other 50% of users will have restricted viewing access to certain documents/pages and be able to write to a database.
I got all of this working fine, but am concerned about two things I'm doing and whether they're proper:
A logged-in user might get redirected to another page, say PAGE1.PHP. I don't want them to be able to save the URL for PAGE1.PHP and just go directly there, bypassing security, so on PAGE1.PHP I have a check for a log-in cookie I created on INDEX.PHP. If the cookie exists they can go to the page, if not they can't. Is this the right way to do this type of thing?
How do I stop a malicious user from inserting a redirect into one of the many text boxes on my various forms? I need to allow HTML, such as strong, font, background, etc. I've been running all the text box values through a function that checks for possible malicious things, one at a time, such as "meta http" or "anchors" or "java script" but I'm not sure this is the best solution.
Thanks for your help!
$_SESSION will be your friend. In a normal shared-hosting environment, $_SESSION may not last any longer than, uh, the current session so plan accordingly. (IE, don't rely on it for anything more than logging in.)
You'll need to read up on session_start and friends.
In addition, check out this discussion: PHP HTML sanitizer for sanitizing HTML input. (Just as an FYI, there is a reason why bbcode and markdown are so popular.)
No - every client can manipulate his cookies and send everything they want - even a invalid "login" Cookie. You have to store those Information serverside in sessions
You could use strip_tags to only allow some Special tags or use a html sanitizer
1 . Upon successful login, store a new $_SESSION variable, say, the user ID (since that seems to be needed often)
Example:
if(login is successful)
{
$_SESSION['userId'] = $userId;
}
Create a php auth page that checks to make sure the session var is populated. If not, redirect to access denied or login page.
Example:
if(! isset($_SESSION['userId']) || $_SESSION['userId'] == '')
{
header("Location: accessDenied.php?msg=Not logged in");
}
On each secure page, require('auth.php');
2 . You can use strip_tags on the textbox, and mysqli_real_escape_string on user-input that ends up going to the database. (Or use prepared statements, see Best way to prevent SQL Injection in PHP)

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

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.

PHP: Put balance of user into session variable

I'm currently optimizing my web site. I'm using a simple credit system that gives you access to certain pages only if you have paid for them. Right now I'm always checking in the DB if the subscription is expired. I do this for multiple pages.
Would it be a good idea to check it only once when the user logs himself in and then carry the result in a session variable?
That would be a bad idea since it's easily exploitable. A user can remain logged in for a long time, perhaps infinitely, if he wanted to. You should keep it the way it is.
Not a great idea, unless you make provisions to refresh that value in the session periodically. Otherwise, a user will be able to extend a subscription's lifetime, potentially indefinitely, by keeping a session active.

Categories