Home Backend Development PHP Tutorial Detailed analysis of PHP session_PHP tutorial

Detailed analysis of PHP session_PHP tutorial

Jul 13, 2016 pm 05:48 PM
php session analyze principle Work document server of detailed

1. How PHP session works
Session files are stored on the server side. By default, the directory where the SESSION file is saved is specified by session.save_path. The file name is prefixed with sess_, followed by the SESSION ID, such as: sess_c72665af28a8b14c0fe11afe3b59b51b. You can get the user's file and get the value of the variable based on the session id provided by the client. The session id can be sent to the server using the client's cookie or the Query_String of the Http1.1 protocol (which is the part after the "?" of the accessed URL). , and then the server reads the Session directory. In other words, session id is the ID card that obtains the session variable stored on the service.
When the code session_start(); is run, a session file is generated on the server, and a session id uniquely corresponding to it is generated. The session variable is defined to be stored in the session file just generated in a certain form. Through the session id, the defined variables can be retrieved. After crossing the page, in order to use the session, you must execute session_start() again; another session file will be generated, and the corresponding session id will be generated accordingly. Using this session id, you cannot retrieve the first session file mentioned above. variable in because this session id is not the "key" to open it. If you add the code session_id($session id); before session_start();, a new session file will not be generated, and the session file corresponding to this id will be read directly.
2. Session common functions and usage
2.1 Session_start(): Start a session or return an existing session.
This function has no parameters and the return value is true. If you use a cookie-based session, the browser cannot produce any output before using Session_start(). You can enable session.auto_start=1 in php.ini, so that you do not need to call session_start() every time you use the session. But there are some limitations to enabling this option. If session.auto_start is indeed enabled, you cannot put objects into the session because the class definition must be loaded before starting the session to recreate the object in the session.
2.2 Register SESSION variable:
PHP5 uses $_SESSION[‘xxx’]=xxx to register the SESSION global variable. Note session_register(),
session_unregister, session_is_registered are no longer used under php5, unless
is changed in php.ini Register_globle is set to on, but for security reasons, it is strongly recommended to turn register_globle off.
The use of HTTP_SESSION_VARS is no longer recommended, and the official recommendation is to use $_SESSION instead.
Page1.php
session_start(); //This function must be called before using SESSION.
$_SESSION[‘name’]=”I am Black Tornado Li Kui!”; //Register a SESSION variable
$_SESSION[‘passwd’]=”mynameislikui”;
$_SESSION[‘time’]=time();
//If the client supports cookies, the session can be passed to the next page through this link.
echo '
Pass SESSION through COOKIE';
//When the client does not support cookies, use this method to pass the session.
echo '
Pass SESSION through URL';
Page2.php
session_start();
echo $_SESSION['name'];
echo $_SESSION['passwd'];
echo date('Y m d H:i:s', $_SESSION['time']);
echo '
Return to the previous page';
?>
2.3 session_id ([ string $id ] ): Get and/or set the current session id
In php5, you can either use session_id() or obtain the session_id and session_name of the current session through the SID attached to the url.
If session_id() has a specific value (that is, the parameter $id is specified), it will replace the current session_id value. The session must be started before using this function: session_start();
Example: Manually set the Session lifetime:
session_start();
//Save for one day
$lifeTime = 24 * 3600;
setcookie(session_name(), session_id(), time() $lifeTime, "/");
?>
In fact, Session also provides a function session_set_cookie_params(); to set the lifetime of Session. This function must be called before the session_start() function is called:
//Save for one day
$lifeTime = 24 * 3600;
session_set_cookie_params($lifeTime);
session_start();
$_SESSION["admin"] = true;
?>
If the client uses IE 6.0, the session_set_cookie_params(); function will have some problems setting cookies, so we still call the setcookie function manually to create cookies.
2.4 Check whether the session exists?
In previous PHP versions, session_is_register() was usually used to check whether the session exists. If you use $_SESSION[‘XXX’]=XXX to register session variables, the session_is_register() function no longer works. You can use
isset($_SESSION[‘xxx’]) instead.
2.5 Change session_id session_regenerate_id([bool $delete_old_session]) Returns true if the change is successful and false if it fails.
Use this function to change the session_id for the current session, but other information of the current session will not be changed by default unless $delete_old_session is true. For example:
session_start();
$old_sessionid = session_id();
session_regenerate_id();
$new_sessionid = session_id();
echo "Original SessionID: $old_sessionid
";
echo "New SessionID: $new_sessionid
";
echo"

";<br>
print_r($_SESSION);<br>
echo"
";
?>
2.6 session_name() returns the name of the current session or changes the name of the current session. If you want to change the name of the current session, this function must be called before session_start(). Note: session_name cannot only consist of numbers, it must contain at least one letter. Otherwise, a new session id will be generated every time.
Example of renaming session:
$previous_name = session_name("WebsiteID");
echo "The new session name is: $previous_name
";
?>

2.7 How to delete session
(1) unset ($_SESSION['xxx']) deletes a single session, unset ($_SESSION['xxx']) is used to unregister a registered session variable. Its function is the same as session_unregister(). session_unregister() is no longer used in PHP5 and can be relegated to obsolescence.
unset($_SESSION) This function must not be used, it will destroy the global variable $_SESSION, and there is no feasible way to restore it. Users can no longer register the $_SESSION variable either.
(2) $_SESSION=array() delete multiple sessions
(3) session_destroy() ends the current session and clears all resources in the session. This function will not unset the global variables related to the current session, nor will it delete the client's session cookie. PHP's default session is based on cookies. If you want to delete cookies, you must use the setcookie() function.
The following is the official PHP case on deleting session:
//Initialize session.
session_start();
/*** Delete all session variables. You can also use unset($_SESSION[xxx]) to delete them one by one. ****/
$_SESSION = array();
/***Delete session id. Since session is cookie-based by default, use setcookie to delete the cookie containing session id.***/
if (isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time()-42000, '/');
}
//Finally destroy the session completely.
session_destroy();
?>
From this we can derive the steps to delete Session:
①session_start()
②$_SESSION=array()/unset($_SESSION['xxx'])
③session_destroy()

3. Session cross-page delivery problem:
3.1 There are two ways to pass a session ID: cookie URL parameter
The session module supports both methods. Cookies are more optimized, but since they are not always available, alternatives are also provided. The second method embeds the session ID directly into the middle of the URL.
PHP can convert links between pages transparently. If you use a version lower than PHP 4.2, you need to manually activate it when compiling PHP. Under Unix, use the --enable-trans-sid configuration option. If this configuration option and the runtime option session.use_trans_sid are both enabled (modify php.ini), the relative URI will automatically be modified to include the session ID.
Note: Non-relative URLs are assumed to point to external sites and therefore do not have a SID appended as this could be a security risk leaking the SID to different servers.
Alternatively, you can also use a constant SID. If the client does not send a session cookie, the SID is in the format session_name=session_id, otherwise it is an empty string. Therefore it can be embedded into the URL unconditionally.
3. 2 Three ways to solve the problem of cross-page session transfer
①The client has disabled cookies.
②There is a problem with the browser and it is temporarily unable to access cookies
③session.use_trans_sid = 0 in php.ini or the --enable-trans-sid option is not turned on when compiling
When the client's cookies are disabled or there is a problem, PHP will automatically attach the session id to the URL, so that the session variable can be used across pages through the session id. But this attachment also has certain conditions: "session.use_trans_sid = 1 in php.ini or the --enable-trans-sid option is turned on when compiling";
After understanding the above principles, we can come up with three ways to solve the problem of session cross-page transfer:
1. Set session.use_trans_sid = 1 in php.ini or turn on the --enable-trans-sid option when compiling to let PHP automatically pass the session id across pages.
(Someone said: But during testing, the method of modifying php.ini to use header('location: xx.php') and javascript window.location=xx.php in the page did not achieve the desired effect. Currently Found normal in xx )
. 2. Manually pass the value through the URL and pass the session id through the hidden form.
3. Save session_id in a file, database, etc., and call it manually during the cross-page process.
Here’s an example:
The first situation:
page1.php
session_start();
$_SESSION['var1']="People's Republic of China";
$url="Next page";
echo $url;
?>
page2.php
session_start();
echo "The value of the session variable var1 passed is: ".$_SESSION['var1'];
?>
Run the above code, and if the client cookie is normal, you should be able to get the result "People's Republic of China".
Now if you manually close the cookie on the client and run it again, you may not get the result. If you can't get the result, then "set session.use_trans_sid = 1 in php.ini or turn on the --enable-trans-sid option when compiling", and you will get the result "People's Republic of China"
The second way:
s1.php
session_start();
$_SESSION['var1']="People's Republic of China";
$sn = session_id();
//PHP5 defines a constant SID to represent session_id(), $url can also be written as $url='Next page' ;
$url="Next page";
echo $url;
?>


s2.php
session_id($_GET['s']);
session_start();
echo "The value of the session variable var1 passed is: www.2cto.com".$_SESSION['var1'];
?>

The third way:
login.html



Login



Please log in:

Username:

Password:






mylogin1.php
$name=$_POST['name'];
$pass=$_POST['pass'];
if(!$name || !$pass) {
echo "The username or password is empty, pleaselog in again";
die();
}
if (!($name=="laogong" && $pass=="123")) {
echo "The username or password is incorrect, pleaselog in again";
die();
}
//Registered user
ob_start();  session_start();
$_SESSION['user']= $name;
$psid=session_id();
$fp=fopen("e:\tmp\phpsid.txt","w ");
fwrite($fp,$psid);
fclose($fp);
//Identity verification successful, perform related operations
echo "Logged in
";
echo "Next page";
?>
mylogin2.php

$fp=fopen("e:\tmp\phpsid.txt","r");
$sid=fread($fp,1024);
fclose($fp);
session_id($sid);
session_start();
if(isset($_SESSION['user']) && $_SESSION['user']="laogong" ) {
echo "Logged in!";
}
else {
//Successfully log in to perform related operations
echo "Not logged in, no access rights";
echo "Pleaselog in and browse";
die();
}
?>
4. Solution to multiple servers sharing the same session
Slightly larger websites usually have several servers. Each server runs modules with different functions and uses different second-level domain names. However, for a comprehensive website, the user system is unified, that is, a set of user names, The password can be used to log in to all modules of the entire website. It is relatively easy for each server to share user data. You only need to put a database server on the back end, and each server can access user data through a unified interface. But there is still a problem, that is, after the user logs in to this server, when entering other modules of another server, he still needs to log in again. This is a one-time login, and all common problems are mapped to technology. In fact, it is between various servers. How to share SESSION data.
If you want to share SESSION data, you must achieve two goals: One is that the SESSION ID generated by each server for the same client must be the same and can be passed through the same COOKIE, which means that each server must be able to read the same SESSION ID. COOKIE named PHPSESSID; the other is that the storage method/location of SESSION data must ensure that each server can access it. Simply put, multiple servers share the client's SESSION ID and must also share the server's SESSION data.
The realization of the first goal is actually very simple. You only need to specially set the domain of the COOKIE. By default, the domain of the COOKIE is the domain name/IP address of the current server. If the domain is different, the domain of each server will be different. The set COOKIE cannot be accessed by each other. For example, the server of www.2cto.com cannot read or write the COOKIE set by the server of www.bbb.com. The servers of the same website we are talking about here have their own particularity, that is, they belong to the same first-level domain. For example: aaa.infor96.com and www.infor96.com both belong to the domain .infor96.com, then we can Set the domain of the COOKIE to .infor96.com, so that aaa.infor96.com, www.infor96.com, etc. can access this COOKIE. The setting method in PHP code is as follows:
CODE:
ini_set('session.cookie_domain', '.infor96.com');
The second goal can be achieved using file sharing methods, such as NFS, but the setup and operation are somewhat complicated. We can refer to the previously mentioned method of unifying the user system, that is, using a database to save SESSION data, so that each server can easily access the same data source and obtain the same SESSION data.
For information on how to put sessions into the database, please see "php Programming" and the following web page
http://www.eb163.com/article.php?id=75&PHPSESSID=d226cc07cec0580ec7dad47119ee4667 Excerpted from Heda Li Xin’s Crazy Coding Life


www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/478394.htmlTechArticle1. PHP session working principle Session files are stored on the server side. By default, the directory where the SESSION file is saved is specified by session.save_path. The file name is prefixed with sess_, followed by S...
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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Hot Topics

Java Tutorial
1668
14
PHP Tutorial
1273
29
C# Tutorial
1255
24
PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

See all articles