Conversation

Your input fuels progress! Share your tips or experiences on prioritizing mental wellness at work. Let's inspire change together!

Join the discussion and share your insights now!

Comments 0

Sharpen your coding skills—try JavaScript challenges on TOOLX now!

advertisement

Session Management in PHP

session in php


Sessions are similar to cookie and enable the functionality of storing temporary user information. The only difference between cookies and sessions is that pertinent cookies store information on the local computer, whereas a session enables PHP to store information on the Web server. Web browsers and Web servers have a stateless interaction and do not maintain track of user sessions. HTTP is a stateless protocol that enables Web browsers to communicate with Web servers. This protocol has no methods or functions to maintain the status of a particular user; even the Web server cannot distinguish user-specific data. However, users can navigate and find information using hyperlinks.

Websites that require complex user 
interaction need session tracking and cannot depend on HTTP or Web servers. Sessions allow websites to store user requests and information on the Web server. A session refers to the total time the user accesses information on a particular Website before exiting the Website. The session is used to manage data for a particular user in a specific session. management is PHP sessions enable distinguishing user-specific information for the entire duration of the session.

Importance of a Session

Consider an example, in a particular Website, the user has to first register and then log on to access any information. For such authentication procedures, the state of the user has to be maintained across the Website. Websites traditionally use GET and POST methods to pass user information from one script to another. When these methods are used, PHP assigns user information variables in the following format:

$name = $_GET['name'];

Cookies 
enable the storage of data into a variable and access it across all the pages of the website. Cookies are prone to security risks because the user information is saved at the client end. The risks involved are greater when users access Websites from a public computer or a shared computer.

For example, a user purchases an item from a Website from a shared computer. While 
placing the order, the user enters all his personal information, such as name and age, address, and credit card information. All these personal details are stored in cookies on the shared computer leaving it vulnerable to misuse by another user.

Following are a few other
 disadvantages of using cookies:

  • Deletion of cookies - Users can easily delete cookies from a client system.  Cookies are created in temporary file folders. Users often delete temporary Internet files to improve the performance of the system. Then, the Websites allot a new cookie to the user.

  • Multiple cookies to the same user - Cookies enable Websites to identify users according to their computers. Websites allot a different cookie to the same person every time the user accesses the Website from different computers. The statistics of the Website record a new user entry for the same person using a different computer. In addition, a user has to set all preferences again on different computers to visit the same Website.

  • Size of the cookie - The amount of information stored in the cookie determines the size of the cookie. The size of the cookie determines the size of the Web page. Therefore, the size of the Web page increases the large amount of information stored in a cookie. The increase in filesize of the Web page results in poor performance.

  • Cookies disabled - Websites store cookies on the hard disk of the client. This reduces the performance of computers with a low memory space. To improve the performance of such computers, users disable cookies. This makes the process of assigning cookies pointless.

Sessions play an important role in such situations. The security of the Website increases because unauthorized users cannot access the information. Sessions eliminate deletion and assignment of new cookies to the same user. The size of a cookie does not affect the performance of a Website. Both the Web server and Web browser benefit because statistical information in the server database is accurate. The user information is not lost from the server database.

Difference between cookies and sessions:

Cookie:

  • Stores user information on the client system(Web browser).
  • Available even after the user exits the web browser.
  • Users can disable cookies.
  • Have size limits.

Sessions:

  • Stores user information on the Web server.
  • Destroyed when the user exits the web browser.
  • The user cannot disable sessions.
  • Do not have size limits.

Working with Session

A session commences when a user accesses a session-enabled Website. The web server assigns a unique session ID to each user when the user starts a session. The scripts store and access user information through the session ID depending on the following two situations:

  • Cookies enabled - The web server allows a session ID to the Web browser through a cookie, using the setcookie() function. Cookies enable the transfer of user information between the browser and the server. PHP stores session IDs in cookies. The scripts access the required information through cookies.

  • Cookies disabled - The web server allows a session ID to the browser using the URL. The URL transfers user information from the browser to the server. PHP stores the session variables in a file and names the file based on the session ID. The scripts access the required user information by retrieving it through the URL.

While using a session, PHP stores all the user information in a file on the Webserver. The file includes a session ID that is related to the user's session variable. Each session ID identifies a different user and relates to a file that belongs to that user. Therefore, a session ID is referred to as a key that links user and user data. PHPdestroys the session file once the user exits the Website.

PHP works with sessions in the 
following sequence:

  • The user accesses a session-enabled website.
  • The Website checks the user identity if the user is a new visitor or an ongoing session user.
  • If the user is a new visitor, the website allocates a unique session ID to the user. The Website saves a cookie containing the session ID on the Web browser. The PHP engine creates a file that stores the session-related variables on the Web server.
  • The Web browser records the cookie that holds the session ID. The browser uses the same cookie to retrieve the session ID and record all the session-related information.
  • The session file is destroyed from the Web server when the user exits from the Website.

Lifecycle of a Session

There are three stages in the lifecycle of sessions based on the communication between the web browser and the web server. They are as follows:

  • Starting the Session
  • Registering the session variable
  • Ending the session

1. Starting the session

A session starts when a user logs on to the Website. In PHP, the session_start() function enables to start of a session. The process of starting a session is also called initializing a session.php creates a session file on the Web server when a new session starts. The session file is created in the /tmp directory. PHP assigns a name to this file based on the unique session identifier value generated by the PHP engine. The session identifier is also known as the session ID. The session ID is a hexadecimal string of 32 digits.

The 
session file name is always preceded by sess_ and is followed by a random 32-digit hexadecimal value. For example, sess_denkhu7869jhnkh789jas543hk87p5u3 is a session file name with session ID denkhu7869jhnkh789jas 543hk87p5u3.The Web server passes the session ID as a response to the browser. The set-cookie header field is sent along with the session ID. The response sets up a session cookie in the browser with the name PHPSESSID and the value of the identifier.

The 
session_start() function must be specified on the top of every Web page or before the start of the actual coding. The session_start() function always returns True. When the session starts, PHP checks for the validity of the session. If the session is valid and exists, it activates the frozen variables of the session. If the session is invalid or does not exist, it creates a session ID for the new session. The scripts can use the session variables only when the variables are registered with the session library. Syntax for the session_start() function is as follows:

session_start();

2. Registering the session variable

Variables in a session file contain user-specific information. To work with the sessions across all the Web pages, session variables need to be registered with the session library. Session library enables the creation, serialization, and storage of session data.

Methods used to set a session variable are as follows:

  • $_SESSION[]-recommended for PHP 4.1.0
  • $HTTP_SESSION_VARS[] - Recommended for PHP 4.0.6 or less
  • session_register() - not recommended as it has been deprecated

Session variables can be of any data type such as integer, string, Boolean, or object. PHP stores the session variables in a session file by serializing the values. PHP automatically handles the process of serializing the session variables.

3. Ending the session

When the user logs out of the Website, the PHP script executes the session_destroy() function. This function removes the session file from the system. Although the session file is deleted, the $PHPSESID cookie is not removed from the Web browser. The session must be initialized before the session_destroy() function is called.


PHP session session in php session management in php what is session in php how it works how to use session in php introduction to session working with session lifecycle of a session

advertisement