- Функции для работы с сессиями
- PHP Sessions
- What is a PHP Session?
- Start a PHP Session
- Example
- Get PHP Session Variable Values
- Example
- Example
- Modify a PHP Session Variable
- Example
- Destroy a PHP Session
- Example
- How to Use Sessions and Session Variables in PHP
- Cookies vs. Session Variables
- What Is a Session in PHP?
- Login Flow With Sessions and Cookies
- How to Start a Session
- Use the session_start Function
Функции для работы с сессиями
Be aware of the fact that absolute URLs are NOT automatically rewritten to contain the SID.
Of course, it says so in the documentation (‘Passing the Session Id’) and of course it makes perfectly sense to have that restriction, but here’s what happened to me:
I have been using sessions for quite a while without problems. When I used a global configuration file to be included in all my scripts, it contained a line like this:
which was used to make sure that all automatically generated links had the right prefix (just like $cfg[‘PmaAbsoluteUri’] works in phpMyAdmin). After introducing that variable, no link would pass the SID anymore, causing every script to return to the login page. It took me hours (!!) to recognize that this wasn’t a bug in my code or some misconfiguration in php.ini and then still some more time to find out what it was. The above restriction had completely slipped from my mind (if it ever was there. )
Skipping the ‘http:’ did the job.
OK, it was my own mistake, of course, but it just shows you how easily one can sabotage his own work for hours. Just don’t do it 😉
Sessions and browser’s tabs
May you have noticed when you open your website in two or more tabs in Firefox, Opera, IE 7.0 or use ‘Control+N’ in IE 6.0 to open a new window, it is using the same cookie or is passing the same session id, so the another tab is just a copy of the previous tab. What you do in one will affect the another and vice-versa. Even if you open Firefox again, it will use the same cookie of the previous session. But that is not what you need mostly of time, specially when you want to copy information from one place to another in your web application. This occurs because the default session name is «PHPSESSID» and all tabs will use it. There is a workaround and it rely only on changing the session’s name.
Put these lines in the top of your main script (the script that call the subscripts) or on top of each script you have:
if( version_compare ( phpversion (), ‘4.3.0’ )>= 0 ) <
if(! ereg ( ‘^SESS4+$’ , $_REQUEST [ ‘SESSION_NAME’ ])) <
$_REQUEST [ ‘SESSION_NAME’ ]= ‘SESS’ . uniqid ( » );
>
output_add_rewrite_var ( ‘SESSION_NAME’ , $_REQUEST [ ‘SESSION_NAME’ ]);
session_name ( $_REQUEST [ ‘SESSION_NAME’ ]);
>
?>
How it works:
First we compare if the PHP version is at least 4.3.0 (the function output_add_rewrite_var() is not available before this release).
After we check if the SESSION_NAME element in $_REQUEST array is a valid string in the format «SESSIONxxxxx», where xxxxx is an unique id, generated by the script. If SESSION_NAME is not valid (ie. not set yet), we set a value to it.
uniqid(») will generate an unique id for a new session name. It don’t need to be too strong like uniqid(rand(),TRUE), because all security rely in the session id, not in the session name. We only need here a different id for each session we open. Even getmypid() is enough to be used for this, but I don’t know if this may post a treat to the web server. I don’t think so.
output_add_rewrite_var() will add automatically a pair of ‘SESSION_NAME=SESSxxxxx’ to each link and web form in your website. But to work properly, you will need to add it manually to any header(‘location’) and Javascript code you have, like this:
The last function, session_name() will define the name of the actual session that the script will use.
So, every link, form, header() and Javascript code will forward the SESSION_NAME value to the next script and it will know which is the session it must use. If none is given, it will generate a new one (and so, create a new session to a new tab).
May you are asking why not use a cookie to pass the SESSION_NAME along with the session id instead. Well, the problem with cookie is that all tabs will share the same cookie to do it, and the sessions will mix anyway. Cookies will work partially if you set them in different paths and each cookie will be available in their own directories. But this will not make sessions in each tab completly separated from each other. Passing the session name through URL via GET and POST is the best way, I think.
PHP Sessions
A session is a way to store information (in variables) to be used across multiple pages.
Unlike a cookie, the information is not stored on the users computer.
What is a PHP Session?
When you work with an application, you open it, do some changes, and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are or what you do, because the HTTP address doesn’t maintain state.
Session variables solve this problem by storing user information to be used across multiple pages (e.g. username, favorite color, etc). By default, session variables last until the user closes the browser.
So; Session variables hold information about one single user, and are available to all pages in one application.
Tip: If you need a permanent storage, you may want to store the data in a database.
Start a PHP Session
A session is started with the session_start() function.
Session variables are set with the PHP global variable: $_SESSION.
Now, let’s create a new page called «demo_session1.php». In this page, we start a new PHP session and set some session variables:
Example
// Set session variables
$_SESSION[«favcolor»] = «green»;
$_SESSION[«favanimal»] = «cat»;
echo «Session variables are set.»;
?>
Note: The session_start() function must be the very first thing in your document. Before any HTML tags.
Get PHP Session Variable Values
Next, we create another page called «demo_session2.php». From this page, we will access the session information we set on the first page («demo_session1.php»).
Notice that session variables are not passed individually to each new page, instead they are retrieved from the session we open at the beginning of each page ( session_start() ).
Also notice that all session variable values are stored in the global $_SESSION variable:
Example
// Echo session variables that were set on previous page
echo «Favorite color is » . $_SESSION[«favcolor»] . «.
«;
echo «Favorite animal is » . $_SESSION[«favanimal»] . «.»;
?>
Another way to show all the session variable values for a user session is to run the following code:
Example
How does it work? How does it know it’s me?
Most sessions set a user-key on the user’s computer that looks something like this: 765487cf34ert8dede5a562e4f3a7e12. Then, when a session is opened on another page, it scans the computer for a user-key. If there is a match, it accesses that session, if not, it starts a new session.
Modify a PHP Session Variable
To change a session variable, just overwrite it:
Example
// to change a session variable, just overwrite it
$_SESSION[«favcolor»] = «yellow»;
print_r($_SESSION);
?>
Destroy a PHP Session
To remove all global session variables and destroy the session, use session_unset() and session_destroy() :
Example
// remove all session variables
session_unset();
// destroy the session
session_destroy();
?>
How to Use Sessions and Session Variables in PHP
Sajal Soni Last updated Feb 16, 2021
Session handling is a key concept in PHP that enables user information to be persisted across all the pages of a website or app. In this post, you’ll learn the basics of session handling in PHP.
We’ll start with an explanation of how sessions work and how they are related to cookies. Then we’ll look at a few code snippets that demonstrate how to work with sessions. You’ll learn how to create and destroy sessions, and how to change session variables.
Cookies vs. Session Variables
Not sure if you need cookies or session variables? Session variables are a way to store data about a user in a database and retrieve it later. Cookies are a way to store data about a user on the user’s computer. Session variables are typically used in applications that need to keep track of a user’s activity. Cookies are typically used in applications that need to store information about a user for a single site.
You can also learn about session variables in my post on using cookies in PHP.
What Is a Session in PHP?
A session is a mechanism to persist information across different web pages to identify users as they navigate a site or app. Are you wondering why sessions are needed for a website? To see why sessions are necessary, we have to go back and see how the HTTP protocol is designed to work.
The HTTP protocol is a stateless protocol, which means that there’s no way a server can remember a specific user between multiple requests. For example, when you access a web page, the server is just responsible for providing the contents of the requested page. So when you access other pages of the same website, the web server interprets each and every request separately, as if they were unrelated to one another. There’s no way for the server to know that each request originated from the same user.
The following diagram depicts the HTTP protocol in a nutshell.
In this model, if you wanted to display user-specific information, you’d have to authenticate a user in each request. Imagine if you had to type your username and password on every page that displayed your profile information! Yes, it would be cumbersome and not practical at all, and that’s where sessions come into the picture.
A session allows you to share information across different pages of a single site or app—thus it helps maintain state. This lets the server know that all requests originate from the same user, thus allowing the site to display user-specific information and preferences.
Login Flow With Sessions and Cookies
Let’s quickly go through a common login flow for a website to understand what happens behind the scenes.
- A user opens the login page of a website.
- After submitting the login form, a server on the other end authenticates the request by validating the credentials that were entered.
- If the credentials entered by the user are valid, the server creates a new session. The server generates a unique random number, which is called a session id. It also creates a new file on the server which is used to store the session-specific information.
- Next, a session id is passed back to the user, along with whatever resource was requested. Behind the scenes, this session id is sent in the PHPSESSID cookie in the response header.
- When the browser receives the response from the server, it comes across the PHPSESSID cookie header. If cookies are allowed by the browser, it will save this PHPSESSID cookie, which stores the session id passed by the server.
- For subsequent requests, the PHPSESSID cookie is passed back to the server. When the server comes across the PHPSESSID cookie, it will try to initialize a session with that session id. It does so by loading the session file which was created earlier, during session initialization. It will then initialize the super-global array variable $_SESSION with the data stored in the session file.
In this way, the user data is preserved across multiple requests, and the user is kept logged in throughout a session.
The following diagram depicts how the HTTP protocol works with sessions.
Now that you’ve seen a brief introduction to how sessions work, we’ll create a few practical examples to demonstrate how to create and manipulate session variables.
How to Start a Session
In this section, we’ll discuss how to start a session in PHP.
Whenever you want to deal with session variables, you need to make sure that a session is already started. There are a couple of ways you can start a session in PHP.
Use the session_start Function
This is the method that you’ll see most often, where a session is started by the session_start function.