Home Backend Development PHP Tutorial How to maintain SESSION in PHP and some thoughts caused by it_PHP Tutorial

How to maintain SESSION in PHP and some thoughts caused by it_PHP Tutorial

Jul 15, 2016 pm 01:26 PM
php session What think yes of

What is SESSION?

According to the WIKI explanation, SESSION is the interactive information that exists between two communication devices. It is established at a certain time and expires after a certain period of time. Common SESSIONs include: TCP SESSION, WEB SESSION (HTTP SESSION), LOGIN SESSION, etc.

According to the different positions of session implementation in the OSI model, SESSION is mainly divided into several types. One is the application layer session, including WEB SESSION (HTTP SESSION) and telnet remote login session; the session layer implementation includes Session Initiation Protocol (SIP) and Internet Phone Call; implemented at the transport layer are TCP SESSION.

This article mainly discusses WEB SESSION. There are generally two types: client-side SESSION and server-side SESSION. The latter is the most common one provided by Java Beans.

What does SESSION do?

In the computer field, especially in the network, SESSION is particularly widely used. It can also be called a dialogue (Dialogue), session, etc. It generally refers to the state stored between two communication devices. Sometimes it also occurs between the user and the computer (Login SESSION).

Different from stateless communication, SESSION is usually used to store communication status. Therefore, at least one of the two communicating parties needs to store the history of SESSION to achieve communication between the two.

How is SESSION (WEB SESSION) implemented?

When HTTP communication is carried out between the browser and the server, an HTTP Cookie is usually included to identify the status. There is usually a unique SESSIONID. SESSION usually records some verification information and levels of the user.

The most commonly used Http Session Tokens in several programming languages ​​are JSESSIONID (JSP), PHPSESSID (PHP), and ASPSESSIONID (ASP). This identifier is usually generated by a hash function and can uniquely represent the identity of the user. When the server communicates with the client, it is stored on the client as a GET or POST parameter.

There are usually two ways to implement SESSION, server-side SESSION and client-side SESSION. Both methods have their own advantages and disadvantages.

Server-side SESSION is easy to implement and has high efficiency, but when it comes to load balancing or high availability requirements, it is more difficult to handle. It is also unavailable when there is no storage device in the endogenous system. of. Load balancing can be achieved by sharing file systems or forcing customers to log in to only one server, but this will reduce efficiency. For devices without storage, server-side SESSION implementation can also be solved by using RAM (see Reference 6). This method is effective for systems with limited client connections (such as routing or access point devices).

The use of client-side SESSION can solve some problems of server-side SESSION, such as avoiding load balancing algorithms, etc., but it will also cause some problems of its own. Client SESSION uses cookies and encryption technology to save state between different requests. After each dynamic page ends, the current SESSION will be counted and sent back to the client. After each successful request, the cookie will be sent to the server to let the server "remember" the user's identity. The most important issue with client SESSION is security. Once the cookie is hijacked or tampered with, the security of the user's information is lost.

How to set SESSION in PHP?

After setting up the PHP development environment, you can view the SESSION-related parts through phpinfo() including:

SESSION module, in PHP V5.2.9 version, there are a total of 25 variables . Among them, the ones that are often used in daily settings are:

session.cookie_lifetime Set the cookie expiration time for storing SESSIONID

session.name The COOKIE name of SESSION, the default is PHPSESSID

session.save_handler The storage method of SESSION , the default is FILE

session.save_path The default storage under Fedora is /var/lib/php/session

session.gc_probability

session.gc_divisor

session.gc_maxlifetime These three options are used Handle the probability of GC mechanism

session.cache_limiter (nocache, private, private_no_expire, public)

session.cache_expire These two options are used to cache SESSION pages

Let’s consider the first question first, how long does it take for SESSION to expire and how does it expire? If you want to use SESSION in a PHP program, you must first reference session_start(). Once this function is executed, a SESSION file will be generated in the storage directory of SESSION (if a file handler is used). The content inside is empty. At the same time, browse The server will see a cookie named PHPSESSID, which stores a hashed SESSION name.

The expiration of SESSION relies on a garbage collection mechanism (Garbage Collection). After SESSION is created, it is stored as a file on the server. Every time the client script accesses the variables in SESSION, the access time of the SESSION file will be updated. Each visit requests the unique SESSION stored in the server based on the SESSIONID stored on the client. When the client's cookie expires, it is impossible to know which SESSION to access, although the SESSION file on the server has not yet been accessed. Recycling after expiration will cause a waste of server resources.

But at the same time, if we want the user's session to expire immediately, we can achieve this by setting cookies. SESSION recycling is performed every time the page is accessed. The probability of recycling is specified by session.gc_probability, session_gc_divisor, and the default is ±1/100. If set to 1, every time the SESSION is accessed beyond its lifetime, the SESSION will be recycled.

Two requirements: 1. Keep SESSION from expiring or extend SESSION expiration time in PHP; 2. Make SESSION expire immediately.

1. It is very necessary to keep SESSION from expiring and extend the SESSION expiration time in PHP, especially in internal application systems or when there are large forms. Think about your boss filling out a form, and it happens to be lunch time. He keeps the form until he comes back from lunch, fills in the remaining content, and what he sees after submitting is generally a login interface. If we want to improve the user experience, the key is to prevent the boss's form from causing problems. We must extend the life cycle of SESSION.

Keeping SESSION from expiring and extending SESSION expiration time in PHP can be achieved by setting session.gc_maxlifetime. However, you first need to ensure that the client's cookie will not expire before gc executes recycling. By setting a longer gc_maxlifetime, the session lifetime can be extended. However, for applications where not all requests will be kept for a long time, this is obviously not the best choice for server configuration.

We know that the recycling mechanism of SESSION is judged based on the last access time of the SESSION file. If it exceeds maxlifetime, it will be recycled according to the recycling probability. So we only need to visit SESSION regularly, and this can be achieved by refreshing the page. According to this idea, there is a solution.

Use JS to access the page regularly;

Use Iframe to refresh the page regularly;

Use the program directly to send HTTP requests, so as to avoid embedding other elements in the page;

The following is the use of JS Send a request to implement the method of keeping the SESSION from expiring, so that we only need to use the page that requires the SESSION to be maintained for a long time (such as a large form page).

<ol class="dp-c">
<li class="alt"><span><span><script type=</SPAN><SPAN class=string><FONT color=#0000ff>"text/javascript"</FONT></SPAN><SPAN>>  </span></span></li>
<li>
<span>        </span><span class="keyword"><strong><font color="#006699">function</font></strong></span><span> keepMeAlive(imgName){  </span>
</li>
<li class="alt"><span>            myImg = document.getElementById(imgName);  </span></li>
<li>
<span>            </span><span class="keyword"><strong><font color="#006699">if</font></strong></span><span>(myImg) myImg.src = myImg.src.replace(/?.*$/, </span><span class="string"><font color="#0000ff">'?'</font></span><span> + Math.random());  </span>
</li>
<li class="alt"><span>        }  </span></li>
<li><span> </span></li>
<li class="alt">
<span>        window.setInterval(</span><span class="string"><font color="#0000ff">"keepMeAlive('phpImg');"</font></span><span>, 4000);  </span>
</li>
<li><span>    </script>  </span></li>
<li class="alt"><span>    <img id=</SPAN><SPAN class=string><FONT color=#0000ff>"phpImg"</FONT></SPAN><SPAN> src=</SPAN><SPAN class=string><FONT color=#0000ff>"http://www.phpplot.com/phpplot/session/sess_refresh.php?"</FONT></SPAN><SPAN> width=</SPAN><SPAN class=string><FONT color=#0000ff>"1"</FONT></SPAN><SPAN> height=</SPAN><SPAN class=string><FONT color=#0000ff>"1"</FONT></SPAN><SPAN> /> </span></li>
</ol>
Copy after login

A random number is added after the URL to prevent the request for this link from being cached by the browser.

2. There are many ways to make SESSION expire immediately. We can session_destroy(), or we can use the above idea to request a session_destroy page.

Is SESSION safe?

The PHP manual clearly states: SESSION does not guarantee that the information stored in SESSION can only be seen by its creator.

If you want to handle some remote operations securely, HTTPS is the only choice. The most basic thing is, don't think that just because a user's information exists in SESSION, it means that the user must be himself, although the information in SESSION will give you the illusion that he has been verified by user name and password. Therefore, if you need to change the password or something similar, asking the user to re-enter the password is a better choice.

Early Apache versions did not use COOKIE to store PHPSESSID, but used URL-rewrite, that is, each URL will be followed by PHPSESSID= to indicate that it belongs to the activated SESSION. The new version Apache has this property set to off by default.

session.use_trans_id = 0;

So in this sense, extending the SESSION for too long or keeping the SESSION online is always not a good thing for security. The ultimate solution is for the user to submit and jump to the login window. After logging in, they can return to the filling page, and all the data is still there. The implementation of this should not be difficult to solve with Ajax now. The current user data is POSTed to a storage location at certain intervals, whether it is XML or JSON.

Keeping SESSION in PHP:

Methods that can be used when the client does not support JavaScript:

1. Write a floating layer, Displayed at the top level, if the user does not disable JS, let the floating layer disappear;

2. Set all INPUT to disable, and then use JS to set it to enabled;

Both of the above methods are used when JS is disabled, and all functions are unavailable. How to make our application still work normally when JS is disabled seems to be more difficult. You have to weigh the time it takes to achieve this and the results you get.


www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/446605.htmlTechArticleWhat is SESSION? According to WIKI's explanation, SESSION is interactive information that exists between two communication devices. It is established at a certain time and expires after a certain period of time. Common SESSIONs are: T...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles