Set session data in php

Master PHP Sessions: What They Do and How to Start One

If you are an active Internet user, you have probably seen this phrase: Your session has expired. It often shows up when you reopen a page after an extended period of inactivity. As a result, you don’t get automatically logged in, and the functions of a specific webpage are no longer available.

PHP sessions are the reason why data becomes accessible to all webpages of a particular application. That particular data, now held in the form of variables, is temporarily stored on the server. When you close the window or tab of the browser, the session will be finished.

In this tutorial, we will speak about what PHP sessions are, how they start or end. We will also get familiar with PHP session variables and understand what PHP $_SESSION means.

Contents

PHP Sessions: Main Tips

  • A session is a method of storing data (using variables) so the browser can use it throughout multiple webpages.
  • In contrast to cookies, the data is not kept on the user’s system.
  • Session variables contain data about the current user. They are accesible to all pages contained in a single web application.
  • Session data is not permanent, but you can load permanent user data for particular users using databases.

Starting a Session

To start PHP sessions, you must use the function session_start() .

To set session variables, you will need to apply a global PHP $_SESSION variable .

In the example below, we begin the PHP file demo_session1.php. Let’s take a look at how we do just that:

 // Start the session session_start(); ?> html> html> body>  // Set session variables $_SESSION["color"]= "blue"; $_SESSION["animal"]= "dog"; echo "The session variable are set up."; ?> body> html>

Note: The PHP session_start() function has to be the first thing in your document: all HTML tags come after.

Getting Values of Variables

To continue, we create demo_session2.php. Using this file, we will access the data on demo_session1.php. Notice how the session data (in form of variables) must be individually retrieved (PHP session_start() function).

See the example below to get a better understanding on how PHP $_SESSION variable holds all of the session data declared in your files:

 session_start(); ?> html> html> body>  // Echo session variables that were set on previous page echo "The color of my choice is " . $_SESSION["color"] . ".
"
; echo "The animal of my choice is " . $_SESSION["animal"] . "."; ?>
body
> html>

In the script example below, you can see how you can display all of the currently declared session variables:

 session_start(); ?> html> html> body>  print_r($_SESSION); ?> body> html>

Wondering how does a session know whose it is? It is simple: sessions create a user identifier on the users’ computers. It is a string of 32 random characters (for instance, 3c7ght34c3jj9083hjaje2fc650e344t).

Читайте также:  Php front end or back end

When a session starts in another window, it checks for the previously created user identifier and continues if it is found.

  • Easy to use with a learn-by-doing approach
  • Offers quality content
  • Gamified in-browser coding experience
  • The price matches the quality
  • Suitable for learners ranging from beginner to advanced
  • Free certificates of completion
  • Focused on data science skills
  • Flexible learning timetable
  • Simplistic design (no unnecessary information)
  • High-quality courses (even the free ones)
  • Variety of features
  • Nanodegree programs
  • Suitable for enterprises
  • Paid Certificates of completion

Modification of Variables

You can change session variables by merely overwriting them:

 session_start(); ?>    // you can change a session variable by assigning a new value $_SESSION["color"] = "red"; print_r($_SESSION); ?>  

How Session Is Destroyed

session_unset() will remove all of the global variables, while session_destroy() will destroy the session entirely. However, both have a similar effect:

 session_start(); ?> html> html> body>  //remove all session variables session_unset(); // destroy the session session_destroy(); ?> body> html>

PHP Sessions: Summary

  • A method of storing variables that contain data for the browser to use is called a session. This data is not permanent and is not saved in the personal computers of users (unlike cookies).
  • Information about the current user is kept in the session variables and accesible to all the pages of a web application. The global PHP $_SESSION variable stores values of all session variables.
  • To finish the session, you should simply close the window or tab in which a website was loaded.
  • It is possible to load permanent user data for particular users using databases.

Источник

Set session data in php

Sessions are a simple way to store data for individual users against a unique session ID. This can be used to persist state information between page requests. Session IDs are normally sent to the browser via session cookies and the ID is used to retrieve existing session data. The absence of an ID or session cookie lets PHP know to create a new session, and generate a new session ID.

Sessions follow a simple workflow. When a session is started, PHP will either retrieve an existing session using the ID passed (usually from a session cookie) or if no session is passed it will create a new session. PHP will populate the $_SESSION superglobal with any session data after the session has started. When PHP shuts down, it will automatically take the contents of the $_SESSION superglobal, serialize it, and send it for storage using the session save handler.

By default, PHP uses the internal files save handler which is set by session.save_handler. This saves session data on the server at the location specified by the session.save_path configuration directive.

Sessions can be started manually using the session_start() function. If the session.auto_start directive is set to 1 , a session will automatically start on request startup.

Sessions normally shutdown automatically when PHP is finished executing a script, but can be manually shutdown using the session_write_close() function.

Example #1 Registering a variable with $_SESSION .

session_start ();
if (!isset( $_SESSION [ ‘count’ ])) $_SESSION [ ‘count’ ] = 0 ;
> else $_SESSION [ ‘count’ ]++;
>
?>

Example #2 Unregistering a variable with $_SESSION .

Do NOT unset the whole $_SESSION with unset($_SESSION) as this will disable the registering of session variables through the $_SESSION superglobal.

You can’t use references in session variables as there is no feasible way to restore a reference to another variable.

Note:

File based sessions (the default in PHP) lock the session file once a session is opened via session_start() or implicitly via session.auto_start. Once locked, no other script can access the same session file until it has been closed by the first script terminating or calling session_write_close() .

This is most likely to be an issue on Web sites that use AJAX heavily and have multiple concurrent requests. The easiest way to deal with it is to call session_write_close() as soon as any required changes to the session have been made, preferably early in the script. Alternatively, a different session backend that does support concurrency could be used.

User Contributed Notes

Источник

Функции для работы с сессиями

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.

Источник

Оцените статью