The mechanism of sessions in PHP. Sessions in PHP

7.7K

Using a PHP session, the server identifies you and allows you to perform the necessary operations: changing information on various web pages, adding new information, etc. After finishing work on the site, you delete the current session by clicking on the “Logout" button:

What is a PHP session?

A PHP session is a way of storing information in session variables that can be used for authentication across multiple web pages. Unlike cookies, session information is not stored on the user's computer. Instead, the session creates a file on the server in a temporary directory.

This information, stored throughout the session, is available for all web pages of the resource. On the server, the location of the temporary file is determined by the session.save_path parameter in the php.ini configuration file.

When creating a PHP session, the following three steps are performed:

  • When a session is created, PHP generates a unique identifier, which is a random string of 32 hexadecimal numbers. The PHP session lifetime ID looks something like this: 9c8foj87c3jj973actop1re472e8774;
  • The server sends a cookie called PHPSESSID to the user's computer to store a unique session identifier string;
  • The server generates a file in the specified temporary directory that contains the name of the unique session identifier with the prefix session_g. sess_9c8foj87c3jj973actop1re472e8774.

These settings help PHP script extract session variable values ​​from a file. On the client side, PHPSESSID contains the session identifier. It confirms the name of the file to be searched in a specific directory on the server side, from which session variables can be extracted and used for verification.

The user can end the session by clicking the logout button, which calls the session_destroy() function. When the user closes the browser, the PHP session is closed automatically. Otherwise, the server will terminate the session after the specified period of time.

Session syntax in PHP

When PHP authorizes through a session, it is created using the session_start() function and deleted using the session_destroy() function. Global PHP variable, known as $_SESSION, is used to set the values ​​of session variables. You can reset all values ​​set for session variables using the session_unset() function.

Session Operations

We will look at the following operations using a PHP session, as well as examples of them.

  • Starting a PHP session and setting its session variables: a new PHP session is started using the session_start() function. Once a session has been created, its session variables can be set using $_SESSION. We have set the values ​​for the variables “ userID” — “php_user" And " password” — “tutorials”:

PHP sessions - creation A PHP session has been started and session variables have been set!"; ?>

Result: Running the above PHP code on the server will produce the following message:

  • Getting PHP session variable values: It is possible to get the values ​​of the variables that we set during latest PHP authorization sessions. When we open a PHP session at the beginning of each page ( session_start()), the code below must be specified. We retrieve and display these values ​​using the $_SESSION global variable:

PHP session - getting values
"; echo "Password - " . $_SESSION["password"] . "."; ?>

Result: When we run the above PHP code on the server, we will get the following message as a result. The values ​​of the session variables that we set earlier after creating the PHP session are displayed.

  • Updating PHP session variable values: During a session, you can update the values ​​of its variables. First we need to open a PHP session at the beginning of each page ( session_start()). In the code below, we update the values ​​of the variables “ userID” — “new_php_user" And " password” — “education”.

You can print an array of session variables and their values ​​using the print_r($ _SESSION) function, as shown below:

PHP session - changing values
"; print_r($_SESSION); ?>

Result: When we run the above PHP code on the server, we will receive the following message. It will contain an array of session variables with their new values.

Website security is based on session management. When a user connects to a secure site, they provide credentials, typically in the form of a username and password. The web server has no idea which user is already logged in or how they navigate from page to page. The session mechanism prevents users from having to enter a password every time they want to perform a new action or go to a new page.

Essentially, session management ensures that the currently connected user is the one who was authenticated. But unfortunately, sessions have become an obvious target for hackers because they can allow access to a web server without the need for authentication.

After the user is authenticated, the web server provides him with a session ID. This ID is stored in the browser and is substituted whenever authentication is needed. This allows you to avoid repeated login/password entry processes. All this happens in background and does not cause discomfort to the user. Imagine if you entered your username and password every time you browsed new page!

In this article I will try to outline all the ways I know to protect the session ID in PHP.

Use of cookies

By default, all session information, including ID, is passed to the cookie. But this doesn't always happen. Some users disable cookies in their browsers. In this case, the browser will pass the session ID in the URL.

Here the ID is transmitted in clear text, as opposed to a session via a cookie, when the information is hidden in the HTTP header. The most in a simple way protection from this will be to prohibit the transmission of the session identifier through address bar. This can be done by writing the following in the Apache server .htaccess configuration file:

Php_flag session.use_only_cookies on

Using encryption

If your site must process sensitive information such as numbers credit cards(hello from Sony), you should use SSL3.0 or TSL1.0 encryption. To do this, when setting a cookie, you must specify true for the secure parameter.

If you store the session password in the $_SESSION variable (it’s still better to use sql), then you shouldn’t store it in clear text.

If ($_SESSION["password"] == $userpass) ( // code )

The above code is not secure because the password is stored as plain text in a session variable. Instead, use md5 encryption, something like this:

If ($_SESSION["md5password"] == md5($userpass)) ( // code )

Browser check

To block the possibility of using a session from another browser (computer), you should check the user-agent HTTP header field:

Session_start(); if (isset($_SESSION["HTTP_USER_AGENT"])) ( if ($_SESSION["HTTP_USER_AGENT"] != md5($_SERVER["HTTP_USER_AGENT"])) ( // code ) ) else ( $_SESSION["HTTP_USER_AGENT" ] = md5($_SERVER["HTTP_USER_AGENT"] )

Session expiration date

Limit the lifetime of the session, as well as the lifetime of cookies. By default, the session duration is 1440 seconds. You can change this value through php.ini and .htaccess. Example for .htaccess:

# Session lifetime in seconds
php_value session.gc_maxlifetime 3600
# Cookie lifetime in seconds
php_value session.cookie_lifetime 3600

Binding by IP address

In certain situations (not always), you should set the binding to an IP address. Mainly when the number of users is limited and have static IPs. The check can be either based on the list of allowed IP addresses,

Include("ip_list.php"); //$ip_white_list = array ("admin1" => "111.222.333.444", "admin2" => "555.666.777.888"); if(!empty(array_search($_SERVER["REMOTE_ADDR"],$ip_white_list))) ( header("Location: admin.php"); ) else ( echo "ACCESS DENY!"; )

Or by IP address for each request (only for static IP):

If(isset($_SESSION["ip"]) and $_SESSION["ip"] == $_SERVER["REMOTE_ADDR"]) ( header("Location: admin.php"); ) else ( session_unset(); $ _SESSION["ip"] = $_SERVER["REMOTE_ADDR"] )

You should be aware that hacking cannot be completely avoided. You can only make this hack as difficult as possible by any known means. However, you should also not forget about your legal users, so as not to complicate their lives with such protection.

I can't figure out why, but tried all the answers/google.. I didn't find anything. Here's the situation:

Localhost code

Result:

Consistent session_id() through the pages application, and when the page is refreshed. $_COOKIE["PHPSESSID"] matches session_id()

Direct server

Session_start(); echo session_id(); print_r($_COOKIE["PHPSESSID"]);

Result:

session_id() changes on every request, page reload, or visit another page. $_COOKIE["PHPSESSID"] is NULL/empty. The same code is used at the top of the page. no other content.

This issue has given me a real headache, what exact server configuration or error could be causing this? Why is the PHPSESSID cookie empty, I believe this is because the associated session_id() is reset on every request too?

Any help please guys!

EDIT: I made a simple test file with three lines on local remote server. This is not related to my code. $_COOKIE["PHPSESSID"] is still empty and the new session_id() happens on the real host every time it is updated.

error_reporting SET TO ALL I get this on a live host:

Notice: Undefined index: PHPSESSID in /home/vivaplug/public_html/dev/wp-content/plugins/test.php on line 5

Google Chrome Headers

LOCALHOST

Request URL:http://localhost/wp-content/plugins/test.php Request Method:GET Status Code:200 OK Request Headersview source Accept:text/html,application/xhtml+xml,application/xml;q=0.9, image/webp,*/*;q=0.8 Accept-Encoding:gzip,deflate,sdch Accept-Language:en-US,en;q=0.8 Cache-Control:no-cache Connection:keep-alive Cookie:PHPSESSID=68b7m4arpsacks4aetgmd3rs93 Host:localhost Pragma:no-cache User-Agent:Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36 Response Headersview source Cache-Control:no-store, no- cache, must-revalidate, post-check=0, pre-check=0 Connection:Keep-Alive Content-Type:text/html Date:Tue, 05 Nov 2013 07:10:51 GMT Expires:Thu, 19 Nov 1981 08 :52:00 GMT Keep-Alive:timeout=5, max=100 Pragma:no-cache Server:Apache/2.4.4 (Win32) PHP/5.4.16 Transfer-Encoding:chunked X-Powered-By:PHP/5.4 .16

REMOVE SERVER

Request URL:http://vivaplugins.com/dev/wp-content/plugins/test.php Request Method:GET Status Code:200 OK Request Headersview source Accept:text/html,application/xhtml+xml,application/xml; q=0.9,image/webp,*/*;q=0.8 Accept-Encoding:gzip,deflate,sdch Accept-Language:en-US,en;q=0.8 Cache-Control:max-age=0 Connection:keep- alive Host:vivaplugins.com User-Agent:Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36 Response Headersview source Age:0 Cache-Control:no-store, no -cache, must-revalidate, post-check=0, pre-check=0 Content-Encoding:gzip Content-Type:text/html Date:Tue, 05 Nov 2013 07:07:49 GMT Pragma:no-cache Server: Advanced Hosting by http://www.unixy.net/varnish Transfer-Encoding:chunked Vary:Accept-Encoding Via:1.1 varnish X-Cache:HIT X-Cache-Hits:2 X-Cacheable:YES X-Powered-By :PHP/5.4.20 X-Varnish:1984840969 1984839805

From the very beginning, everyone accepted PHP with a bang, but as soon as fairly large projects began to be created in this language, the developers were faced with a new problem - PHP lacked the concept of global variables! That is, a certain script was executed, sent the generated page to the client, and all resources used by this script were destroyed. I’ll try to illustrate: suppose there are two pages of one site, index.php and dothings.php. The sources for these pages look like this:

index.php dothings.php

If we run these two scripts, then on the first page we will see the inscription “I was assigned to index.php”, and the second page will be empty.

Website developers, without thinking twice, began to use cookies to store global variables on the client side. The process looked something like this: the user comes to the main page of the site, does some actions, and all information associated with this user, which may be needed on other pages of the site, will be stored in his browser in the form of cookies. This method has quite serious disadvantages, because of which many developers at one time turned away from PHP. For example, we need to authorize a user to allow him access to private (or private) sections of the site. You will have to send the user a cookie, which will serve as his subsequent identifier on the site. This approach becomes very cumbersome and inconvenient as soon as the site begins to collect more and more information about the user’s behavior, because it is advisable to encode all the information sent to the user so that it cannot be faked. Just recently, by forging cookies, it was possible to “crack” more than one chat, and sometimes even sneak into someone else’s mail. In addition, there are still strange people in the world whose browser does not support cookies.

I will not go into the technological issues of the session mechanism, but will only describe how to correctly work with sessions in PHP.

How to work with sessions?

If you test the examples from the article (or your scripts) on any commercial hosting, there should be no problems with working with sessions. If you set up your server yourself (whether it’s a real server or an emulator), errors with something like this may appear:

"Warning: open(/var/state/php/sess_6f71d1dbb52fa88481e752af7f384db0, O_RDWR) failed: No such file or directory (2)."

This just means that your PHP is configured incorrectly. You can solve this problem by specifying the correct path (to an existing directory) for saving sessions in the php.ini file and restarting the server.

Any script that will use variables (data) from sessions must contain the following line:

Session_start();

This command tells the server that a given page needs all the variables that are associated with a given user (browser). The server takes these variables from the file and makes them available. It is very important to open a session before any data is sent to the user; in practice, this means that it is advisable to call the session_start() function at the very beginning of the page, for example like this:

Session_start(); ?> ... To set the directory in which session files will be saved, use the session_save_path() function: session_save_path($_SERVER["DOCUMENT_ROOT"]."/session"); session_start();

After the session starts, you can set global variables. When assigning any value to any field of the $_SESSION array, a variable with the same name is automatically registered as a session variable. This array is available on all pages using the session. For example, let's look at the program:

index.php Everything is OK. The session has been loaded! Let's go through and see what's there: dothings.php

When running these files sequentially, the first script "index.php" will produce the following result:

Everything is OK. The session has been loaded! Let's go through and see what's there:

And the second “dothings.php” is this:

I was asked to index.php

The $a variable is now available on all pages of a given site that have launched sessions.

Other useful features and techniques for working with sessions:

  • unset($_SESSION["a"])- the session “forgets” the value of the session variable specified;
  • session_destroy()- the session is destroyed (for example, if the user left the system by clicking the “logout” button);
  • session_set_cookie_params (int lifetime [, string path [, string domain]])- using this function you can set how long the session will “live” by setting unix_timestamp, which determines the time of “death” of the session. By default, the session "live" until the client closes the browser window.
  • session_write_close()- recording session variables and closing it. This is necessary to open the site in a new window if the page is taking a long time to process and has blocked the sessions file for your browser.

Examples

Now let's turn to practical application session mechanism. Here we will look at a couple of fairly simple and at the same time useful examples.

User Authorization

Questions about user authorization using PHP sessions are constantly asked at web programming conferences. The mechanism for authorizing users in the system using sessions is quite good from a security point of view (see section).

Our example will consist of three files: index.php, authorize.php and secretplace.php. The index.php file contains a form where the user will enter his username and password. This form will pass data to the authorize.php file, which, if authorization is successful, will allow the user to access the secretplace.php file, and otherwise will display an error message.

Examples: index.php Enter your password

Login:
Password:
authorize.php page... header("Location: secretplace.php"); exit; ) ) // if something was wrong, the user will receive // ​​an error message. ?> You entered the wrong password! secretplace.php Hello,, you're on secret page!!! :)

Safety

So, we are able to pass an identifier from one page (PHP script) to another (until the next call from our site), which means we can distinguish between all site visitors. Since the session identifier is a very large number (128 bits), there is practically no chance that it can be found by brute force. Therefore, the attacker is left with the following options:

  • there is a Trojan on the user’s computer that steals session numbers;
  • the attacker intercepts traffic between the user's computer and the server. Of course, there is a secure (encrypted) SSL protocol, but not everyone uses it;
  • a neighbor approached our user’s computer and stole the session number.

Such situations, based on the fact that someone steals something from someone else, in general, are not within the competence of the programmer. Administrators and users themselves should take care of this.

However, PHP can very often be "tricked". Let's look at possible hacking points in the user authorization program:

  • The authorize.php file is an attempt to guess a password using a third-party script;
  • The file secretplace.php is an attempt to deceive the program by entering the values ​​of the $logged_user variable in the browser address bar, for example like this:
    "http://www.yoursite.ru/secretplace.php? logged_user=hacker"

So, two “holes” are clearly visible in our program, one is small and not particularly noticeable, but the second is simply huge, through which most hackers get into where they don’t need to go.

How to “patch” hole number 1?

We won’t write tons of code to block an IP address, etc., but simply check where the request comes from, or rather what page the request came from, if it’s any page from our site, then everything is fine, but in all other cases We won't let you in. Let's adjust the authorize.php file:

authorize.php V2 page... header("Location: secretplace.php"); exit; ) ) ) ?> You entered the wrong password!
How to get rid of "hole" number 2?

Let's say you have a website where everyone can register to post to a forum. Naturally, in the forum some users (administrators, moderators) have more opportunities than others; for example, they can delete messages from other users. You store the user's access level in the session, in the $user_status variable, where $user_status = 10 corresponds to full access to the system. An attacker who comes to the site just needs to register in the normal way, and then add in the address bar of the browser ?user_status=10. So you have a new admin on your forum!

In principle, any script variable can be set through the address bar by simply adding a question mark and the name of the variable with its value after the full address to the script. Let's fix our code to avoid this:

secretplace.php V2 variable unset($_SESSION["logged_user"]); // open the session session_start(); /* you can’t just go to this page... if the username is not registered, then we redirect him to the index.php page to enter the login and password... here you can actually do a lot of things, for example, remember the user’s IP, and after the third attempts to gain access to files, block it. */ if(!isset($_SESSION["logged_user"]))( header("Location: index.php"); exit; ) ?> Hello,, you are on a secret page! Results

The session mechanism is a pretty good feature of the PHP language. Sessions are simple and very flexible to use. By the way, there is one, little documented feature of PHP sessions (available starting from version 4.0.3) - in sessions you can store not only variables, but also objects.

Examples

?>
// Automatically insert SID into links. ini_set("session.use_trans_sid", true); session_start(); ?> Click here!
Click here!!

// An example of working with sessions. session_start(); // If you have just visited the site, reset the counter. if (!isset($_SESSION["count"])) $_SESSION["count"] = 0; //Increase the counter in the session. $_SESSION["count"] = $_SESSION["count"] + 1; ?>

Counter

time(s).
Close your browser to reset the counter.
" target="_blank"> Open a child browser window.
// A simple example of using sessions without Cookies. session_name("test"); session_start(); $_SESSION["count"] = @$_SESSION["count"] + 1; ?>

Counter

You have opened this page in your current browser sessiontime(s).
Close your browser to reset this counter.
?">Click here to refresh the page!

Sessions in PHP are a mechanism for storing information about the client's computer on the server side. In fact, sessions in PHP are not such a complex topic, but to understand it you need to know how cookies work in PHP. So, if you don’t know how cookies work in PHP, then read the relevant article first, and then come back here.

The word session is translated from English as session, so the very meaning of sessions in PHP becomes more clear, but programmers have adopted the term “sessions”, and we will use it in this article.

Sessions in PHP are very similar to the cookie mechanism, the same key => value pairs, only they are stored on the server side.

session_start() function

We need to start the session, for this there is the session_start() function. This function starts a session, or session, whatever you want to call it.

It is advisable to call the session_start() function at the very beginning of the page, but in my examples I do not do this.

$_SESSION array

Sessions are groups of variables that are stored on the server but relate to one unique visitor. Again, this is the key point: sessions are stored on the server.

In order to ensure that each visitor interacts with his data from his session, a cookie is used, the command to create which PHP gives itself, you don’t need to worry about it. This cookie is only relevant to the server and cannot be used to obtain user data.

On the server, session data is stored in a text file and is available in the PHP program in the $_SESSION array. To save a variable in a session, you need to assign it a value in this array.

Let's finally start using examples. It's very simple.

Sessions in PHP meaning."; ?>

Now let's try to get the value from the $_SESSION array in another example.

Sessions in PHP

Please note that if in the second example we remove the session_start() function then we will not have access to the data in the $_SESSION array.

session_id() function

Once a session is created, you automatically have access to the session's unique identifier using the session_id() function. This function allows you to both set and get the session ID value.

Sessions in PHP

You can look in the developer toolbar of your browser (in Chrome, press Ctrl + Shift + I, then Resources, and you will find a cookie there), this domain has set a cookie for your browser with the name PHPSESSID and approximately the following value: “7g5df9rkd1hhvr33lq1k6c72p7”.

It is by the PHPSESSID value that the server will determine your browser and work with the corresponding set of variables that will be available to the script through the $_SESSION array, as previously written.

session_name() function

While the session_id() function allows you to get the session ID value, the session_name() function allows you to get the session name.

Sessions in PHP

Once again about the session_start() function

Now we know more about how sessions work in PHP and we need to return to the session_start() function once again. This function initializes the session mechanism for the current user. How exactly does this happen:

  • If the user launched the site for the first time, session_start() sets a cookie on the client and creates temporary storage on the server associated with the user ID.
  • Specifies the store associated with the current ID passed in.
  • If there is data in the storage on the server, it is placed in the $_SESSION array.
  • If register_globals from the php.ini file is On, then all elements of the $_SESSION array are turned into global variables.

Session usage example

Now we will look at an example that will allow us to conduct small experiments with sessions.

Sessions in PHP

Counter

You have opened a page in the current sessiononce.

Open the example in ">this tab.

All session work is based on the $_SESSION array, this is clearly visible in this example.

If you close the browser window, the session will end and our counter will be reset to zero. This behavior of sessions in PHP can be changed; we will return to this issue a little later in the article.

Ending a session

In order to end the session we need:

  1. Clear the $_SESSION array.
  2. Delete temporary storage on the server.
  3. Delete session cookies.

You can clear the $_SESSION array using the session_unset() function.

The session_destroy() function deletes temporary storage on the server. By the way, she doesn't do anything else.

You need to delete a session cookie using the setcookie() function, which we learned in the lesson on working with cookies in PHP.

Example of ending a session:

Ending a session

The session has ended.

Now you can conduct an experiment: run an example with a counter in one window, increase the counter, and then run the example with deleting the session and refresh the page with the counter again.

You can delete a cookie file like this:

setcookie(session_name(), "", time() - 60*60*24*32, "/")

Once again about the session_name() and session_id() functions

The session_name() and session_id() functions are rarely used in practice, but I am writing about them because the article needs to reveal the very mechanism of how sessions work in PHP.

You can use these functions to define your own session names and IDs, but this is not recommended. If you wanted to set them, then write these functions with arguments before the session_start() function, as in the example below:

Sessions in PHP

Using this example, all users will be assigned the same session ID.

Let's take a closer look here: if you run the example from the section about the session_name() function (here is the link) in different browsers (for example, Chrome and Internet Explorer), then each browser will have its own unique session identifier. Browsers store cookies each in their own folder, so the session_start() function will allow each browser to create its own unique identifier and, accordingly, a unique storage will be created for each browser on the server. Therefore, the counter example (this one) will work independently in each browser.

If you set the same session ID for all users, then they will work with the same storage on the server. Here is an example of a counter that will count visits from different browsers:

100) ( session_unset(); session_destroy(); ) ?> Sessions in PHP

Counter No. 2

Opened the page in different browsersonce.

Open the example in ">this tab.

If you run this example, it’s not a fact that you will see one there. Other visitors may have already changed the values ​​in the session store on the server. I don’t know when the server deletes the storage in this case, so if the counter exceeds 100, I will end the session.

Setting the waiting time

By default, the session "live" until the visitor closes the browser window. This is due to the fact that the session_start() function places such a cookie on the client.

The session lifetime can be changed using the session_set_cookie_params() function, here is its syntax.

session_set_cookie_params (int lifetime [, string path [, string domain [, bool secure]]])

In practice, it is enough to use only the first parameter (lifetime), here you write down the time in seconds, which determines how long the server should remember the session state after closing the browser.

The effect of the session_set_cookie_params() function applies only to the period the script is running.

Here is an example of using this function:

Sessions in PHP

Counter No. 3

Counter value:.

Open the counter in ">this tab.

Wind up the counter and close the browser, after 30 seconds open this example again. Your session will be saved.

Share