Conceptual understanding of PHP server session - php

So as a engineer, I usually require a concert understanding to be able to work with something. I feel like I understand the basics of a session. I am wondering about the specifics and details there of.
What are the limitations of a session?
How can I manipulate a session? What can explicitly not be done to or with a session.
What data structures does PHP use to define and manage sessions?
Is a PHP session different from any other session in any significant way?
I understand that these questions are general, so if anyone can simply suggest a good resource I would be thankful. There is plenty of info out there, but it is either too basic or teaching to a specific topic.
Thank you for the help.

Sessions is a way for the server to recognize you so he sends to you a customized version of the page instead of sending always the same page for everybody.
To recognize you one way is he tells the browser to save in your computer a small file with a simple text, and when you visit the page again the server would ask the browser for that file, if the browser sends it, and it contains the expected content, the server can now know this is you again. That are cookies.
Another way to maintain a session, a part from cookies, is the server puts a special unique token for you in the url of all the links the page has. Whenever you browse the site all pages you visit will have that token, the server see it and know it's the token it made to you, so he knows it's you again.
So both with cookies or url-based sessions, the server will have to save info about the sessions opened, for example to store the $_SESSION variables you create in PHP, if you create such a variable the server will save it to a file which he will later identified by your cookie or token content and when you re-visit the page he will read that file and load the $_SESSION variables you create last time.

Here's a good resource: http://php.net/manual/en/book.session.php
What are the limitations of a session?
I don't really know what you mean by that. Limitations in what context?
How can I manipulate a session?
To manipulate values, just use the $_SESSION superglobal directly.
What can explicitly not be done to or with a session?
Again, without context, it's hard to understand what you mean. I guess an important point is that sessions are transient, so you can't explicitly store data you want to keep indefinitely.
What data structures does PHP use to define and manage sessions?
The filesystem.
Is a PHP session different from any other session in any significant way?
What is another session?

http://php.net is the best source for your questions

PHP session is a very nice way of having persistent information on your site for different users.
Check out the PHP session functions you can use.
You can view examples of how to use sessions at php.net.
A session is most commonly associated with user accounts. A user can log into your site, and you create a user session to keep track of their information and make sure they are allowed to be logged in.
The basic assumption is that a session is secure, because the server is aware of the sessions in progress. Utilizing sessions over HTTPS is a fairly secure way of keeping users logged into your site (without HTTPS you run the risk of session hijacking).
The other basic function is to have persistent data about a given user. So let's say you wanted to keep track if the user has submitted a form, you could do:
$_SESSION['form_submitted'] = TRUE;
And now you can check that global variable whenever you want to know if that specific user has submitted the form. So the session (in the same way a cookie is used) allows you to do really cool things that otherwise would not be possible.

Related

Make cookies or stay with sessions encrypted?

In relation to How to create a secure login system using cookies and sessions?
I'm building a simple forum, spending my time securing $_SESSION => hashing as mindful person about security but simple one because my future website will be not something giant, I will enable SSL.
Will I need cookie(s) for example about Google Search Console/day's visitors/SEO or nothing special about that and general security ?
Thank you for your help
The Sessions and Cookies both serve the purpose of storing data.The sessions are made at the server and gets destroyed once the connection with the server is lost or the application is closed, while the cookies are made at the client and stays for a defined time, either the application is opened or closed.And you can delete them anytime you wish.
So in relation to the security, the sessions are more appropriate than the cookies.
The latter part of your question is a kind of vague to me, yet I think this answer will be of some help to you. :D
You can find a Cookies vs. sessions comparison here.
There are three main ways, we can get data from our users.
By typing a url or click a link which will be a GET request.
By submit a form which will be a POST request.
Pulling values out of their browser COOKIE that send with every request they make.
and there is one more method to get data which is -
SESSION
sessions are related to cookies.
A session is a file that stored on the web-server file system not on the browser side.
So, when we want save some information, the process is instead of sending a cookie to the user, we send them as a reference to that session file.
So on every request they make to the web server after that they send the reference and were able to lookup that session file and pull all the data out of it.
So the most important difference with sessions that they stored in server-side not client-side.
All we send to the client is a reference to help us find that file.
Using sessions has some benefits and drawbacks -
PROS -
More storage than cookie.
cookie is limited to 4000 characters maximum.
for session, it is limited to only by the file storage size that you have on a web server i.e; how big is the hard-disk, that's the limit.
Smaller request sizes because session uses reference.
Conceals data values.
More secure, less hackable.
CONS -
Slower to access.
You won't see much difference on camparing to cookies, but it is.
Expires when browser is closed.
Cookie can live 6 months or more.
Session files accumulate.

Is passing session data from one PHP page to another efficient?

I was wondering if using a SESSION variable to pass data from one PHP page to another is efficient. I ask this because I thought that SESSIONS were only used to keep the user logged in to a website, and as an alternative to cookies. Would it not be better to pass data (non-sensitive) from one page to another via a URI such as members.php?name=Joe&age=28?
A PHP session writes a cookie to your browser and then stores the data associated with that session on disk; its about as expensive as an include() to read it back in on the next page load, which is to say completely trivial.
Additionally, the user can't change session data unless you create a mechanism which allows them to; they can mess with the query string easily.
Short answer: Yes, its efficient.
Sessions are useful for lots of things, not just login information. They're great for holding status messages during a POST/redirect/GET cycle or anything else that keeps track of the state of the user's session (hence the name) - but only the current session, not long-term permanent configuration options.
As far as efficiency goes, you need to remember that anything in the session needs to be serialized & unserialized on every page load. Storing a name and age wouldn't add much. Adding a megabyte of image upload would probably be bad.
More important than the efficiency consideration is to remember that session data is only temporarily persistent. If you want to always know that Joe is 28, it should go in the database. If it's only useful on a single page load, it should probably stay in the URL or be POSTed. If you're interested in remembering it for a few minutes, the session might be the place to put it.
Depends on what you're doing. If that page requires that information to function properly and is not behind a login then passing in a query string is the way to go (e.g. search results, product pages). If it is behind a login then using a session would allow you to keep your URLs clean and also make it difficult for users to abuse the page (e.g. swap out data in the query string).
Yes, you can store data and message in SESSION and it is accessible from any page. But remember, SESSION uses browser support to store data. They can be deleted manually by the user

Sessions without passing SID - is it reliable?

I'm working on a project that keeps some user information (non-sensitive) in a php session. As it is my first time working with sessions, I never bothered to pass any Session ID, but it still works - is that right ? I couldn't find any information about that.
I'm using some parts of the information in the $_SESSION variable to navigate and influence some of the sites' behaviour, and it sometimes is crucial for the page to interact with the user. Meaning without the correct informatin of the current session the navigation will be broken.
So, can I rely on the existence of Sessions ?
And can I rely on the server to automatically pick the right session without passing the SID ?
I'm working only on one server and I don't need the session to be restorable (meaning that when a user leaves the application the session can be destroyed).
If you couldn't find information about that, you probably skipped the most obvious reference: the official PHP manual. It's right there in the Introduction of the Sessions chapter:
Session support in PHP consists of a way to preserve certain data
across subsequent accesses. This enables you to build more customized
applications and increase the appeal of your web site.
A visitor accessing your web site is assigned a unique id, the
so-called session id. This is either stored in a cookie on the user
side or is propagated in the URL.
If your question is whether cookies are reliable for this purpose, in fact it's the de-facto standard nowadays. You'll hardly find PHP-powered sites that still transmit the session ID in the URL. The reason is that it's a problematic technique: it's too easy to give away your session ID. If you copy the URL and send a link to a friend or post it in a forum it's very easy that any stranger is able to access your private data, even inadvertently (you don't need a malicious guy here) if they visit the site before the session has expired and the site does not implement further verifications (which is the usual situation).
Yes you can rely to having the server to pick the correct sessions for you. I have in my 10 years of php coding not experienced a faulty session yet.
However, if you choose to pass the sessionid to the next page, be ware of the risks. Session hijacking is a very serious business if you have any sort of private data.

Storing user session variables in file vs in database

I've got a php application and I'm saving the session variables for the user using $_SESSION itself. Is there any particular advantage of storing it in a database?
I'm looking for a reliable / well-researched article which talks more about this. I havent been able to locate anything yet.
The advantage you have of storing it in a database is that the data exists as long as you want it to exist.
Your browser will destroy the session according to how it is setup, which makes it a bit unreliable. I can't however find an article on this yet but this is what I use as a convention for a situation like this.
Any data that needs to be stored long term, like user details and activity I store in a database. Any data that is only relevant to the current workspace, like logging into a site and posting a few comments etc. can be stored in the session. For instance I store user authentication details in a session to constantly check whether the user is logged in or not and whether to redirect him/her to the correct page.
This works wonders when checking access rights throughout your application.
For me its much safer to store user details in a database because it cannot be publically accessed like the $_SESSION.
Please disagree with me if you want to though.
I would say storing in database is better.Because
When you are hosting your site with a shared host
PHP uses the same path for storing sessions for all the users,somewhere that is not in your folders.
You can track the users and their status easily.
For application that are running on multiple servers, you can store
all the session data in one database.
This article may help.
Well this is a question for the ages. Personally from what I have learned in my time. Unless your site starts booming on a massively large scale where you need to start using multiple servers for various aspects of the system such as load balancing where you have many mirror systems running. Or need to improve performance a little for an over populated system the benefits of using DB related sessions or File based sessions really isn't any different.. Grant it I could be wrong this is merely my own personal perception off my own experiences. Just like you Ive never really found any articles, posts, other that really put either to the test side by side hell I don't even think I have found anything that really puts either to the test stand alone for that matter. Personally I just go with what ever the need is (or desire of my client) usually I just stick to native sessions file based.
I hear they can be spoofed, but have seen no proof to that notion to date. So other than that potential I stick with file based. Unless I am using a system like code igniter then sessions seem to handle better DB driven with it rather than not.
At some point in time you're going to have to store something in a session. Whether it's all the session variables or just the ID of a row in a sessions table. That being the case it would be fairly easy to alter the ID stored in a badly encrypted session and hijack a different session.
Consider this:
Full Session Option. This has the User ID, Username and an encrypted and hashed password stored so that every time a page is called it verifies my login. To hijack someone else's session I'd have to know their User ID, Username and Password Hash and be able to overcome the sessions inherent encryption.
Session + DB Option. This just has a Session ID stored that references a row in a database. All I have to do to change the session I want is to break the encryption on the session and say add one to the Session ID. I'd then be authenticated as the user that logged in after me.
You could store login details in a session and then any none login related data in a session table if you have a lot of extra information but then again you might as well just remove the need for an extra table and extract the data from whatever relevant tables you need.
From my short experience, you should store in $_SESSION only data that you will NOT need to be refreshed in all sessions opened by a unique user in different devices.
(mobile/desktop/etc.)
In other words, data that you are sure will never change like a userID.
For example, I had stored the user profile picture path into
$_SESSION and it led to a strange User Experience. When changing the
profile picture in a desktop, it did not refresh the profile picture
for the user on his mobile. Other users saw the new picture though.
Indeed, the path was refreshed into the DB but not in the $_SESSION.
Login-out and Login-in would not change anything.
Remember that the default behavior is that $_SESSION passed with cookie will be different for each browser even if this is the same user logged in. You will have to do a session_destroy() to avoid being stuck with old data.
Very temporary data may be stored in $_SESSION as well I guess.
NB: the basic need of global session, out of these arguments, is to have variables available globally

Create PHP session for all users or only ones who want to log in?

At the moment my CMS creates a PHP session for every user who visits the site. I'm thinking about only creating a session for users who want to log in. The problem I have here is that some UI elements for logged in users are on all pages, so on every page request the system has to check if the user is logged in, which means I have no other option to start a session on every page request? Or am I wrong? Is it normal practise to create a session for every user, even if dose not want to log in?
Short, I'd like to know if A. there is an option in my use case to only create a PHP session for users who want to log in and B. if it consider bad practise creating a session for every user, regardless if he wants to log in or not. If this isn't the case, I can leave things as they are really ...
You have no (real) choice. You can not know, that a user is logged in (or not) without a session.
Quick answer:
In your use case, it is perfectly fine to create a session for every user. Sessions are negligible and not something to worry about as far as performance goes (in your case).
The method you're using is not bad practice at all. In fact I'd say it's pretty near best practice.
Long answer:
In my 6+ years of experience as a PHP programmer in the corporate world, it is perfectly normal to create a session for every user, regardless of whether or not they're logged in. In fact, sessions can be used to do a lot of convenient features for a user even when they're not logged in -- such as shopping carts, etc. You're doing things right. If you want to speed up performance at all, use a tool like Google's Pagespeed and Yahoo's YSlow -- they'll give you tips on best practice for websites.
It is possible to avoid creating a session every time. So what if session files are small? Why proliferate them when it's unnecessary?
This is what I do, in essence:
Check for the existence of the session cookie on the incoming request, and only do the session_start() if you've received one.
Logged-out users browsing the site (typically) won't be sending the session cookie, and so they won't trigger a session_start(). Simple.
Once someone logs into your site and you do want to start a session (session both logically in your application and in the PHP sense) then use session_start() etc which will handle setting up the cookie.
And once someone logs out, make sure you destroy the session cookie too, not just the PHP session itself.
Obviously the user could block your cookie operations at their end and screw things up, but they could do this anyway.
Can't you just look for an empty $_SESSION value to see if they're logged in?
In most cases, logins are managed via the session, therefore you must create a session at the start of the page to determine if they are logged in or not. You have no choice really... It is not bad practise, it is common practise.

Categories