search
HomeBackend DevelopmentPHP TutorialDetailed explanation of how to use php Session variables

Detailed explanation of how to use php Session variables

Jul 09, 2017 pm 02:34 PM
phpsessionInstructions

In phpSession is often used to verify user registration or verification after login. Let me summarize some common examples and usage of session variables

When you run an application, you open it, make changes, and then close it. It's a lot like a session. The computer knows who you are. It knows when you start the application and when it terminates it. But on the Internet, there's a problem: the server doesn't know who you are and what you do, and that's because HTTP addresses don't maintain state.
PHP session solves this problem by storing user information on the server for subsequent use (such as user name, purchased items, etc.). However, session information is temporary and will be deleted after the user leaves the site. If you need to store information permanently, you can store the data in a database.

Copy the manual, try each one and write it out for your own reference. Who told us to just learn it? Session has about 12 functions , which are:

session_start: initial session.
session_destroy: End session.
session_unset: Release session memory.
session_name: Access the current session name.
session_module_name: Access the current session module.
session_save_path: Access the current session path.
session_id: Access the current session code.
session_register: Register new variables.
session_unregister: Delete registered variables.
session_is_registered: Check whether the variable is registered.
session_decode: Session data decoding.
session_encode: Session data encoding.

There is also a global variable: $_SESSION

Before you store user information in the PHP session, you must first start the session.
Note: The session_start() function must be located before the label:

The code is as follows:

<?php session_start(); ?>

<html>
<body>

</body>
</html>

Storage Session variable

The code is as follows:

<?php
session_start();
// store session data
$_SESSION[&#39;views&#39;]=1;
?> 
<html>
<body>

<?php
//retrieve session data
echo "Pageviews=". $_SESSION[&#39;views&#39;];
?>

</body>
</html>
 [html]
终结 Session
unset() 函数用于释放指定的 session 变量:
[code]
<?php
unset($_SESSION[&#39;views&#39;]);
?>

You can also completely terminate the session through the session_destroy() function:

The code is as follows:

<?php
session_destroy();
?>

Example:

The code is as follows:

?> 
<p>假定本页名为temp.php </p> 
<p><a href="temp.php?action=login">用户进行登陆post,<?php 
session_start(); 
switch ( $_GET[&#39;action&#39;] ){ 
case "loginif"; 
//登陆验证,假定session储存的秘密应该等于123才为正确 
if ($_SESSION[&#39;pass&#39;]=="123"){echo "密码正确 您可以执行注销";}else{echo "密码错误,您可以重新登陆";} 
break; 
case "logout"; 
//注销登陆 
session_unset(); 
session_destroy(); 
echo "注销成功!可以判断一下密码是否正确来看看是不是成功注销"; 
break; 
case "login"; 
//写入session以供验证, 
$pass="123";//密码 
$_SESSION[&#39;pass&#39;]=$pass; 
echo "写入登陆密码了 去判断密码成功与否吧。"; 
break; 
} 程序处理写入session</a></p> 
<p><a href="temp.php?action=loginif">判断用户密码是否正确</a></p> 
<p><a href="temp.php?action=logout">登陆成功的用户注销登陆</a></p>

I summarized the usage of session in php.

(1) Start session
Before each use of session, add this sentence: "session_start();". As the name suggests, the function of this function is to start using the session.
(2) Register session
First, create a global (note, it must be defined as global, otherwise it cannot be used on other pages) Array , such as $login, where $login['name ']="Victor", $login['pwd']="111111", and then call the function "session_register(login);", the session is successfully registered.
(3) Using variables in the session
Similar to registering a session, you must first create a global array, and then it is the same as using a normal array.
(4) Determine whether the session is registered
It is very simple, just use "if (session_is_registered(login))" to judge.
(5) Uninstalling session
It’s also very simple, just “session_unregister(login);”.
Note: Be sure to perform (1) before proceeding with (2) (3) (4) (5).

An example is given below:

index.htm

The code is as follows:

<html> 
<head> 
<title>测试</title> 
</head> 
<body> 
<FORM METHOD=POST ACTION="login.php"> 
用户名:<INPUT TYPE="text" NAME="name"><br/> 
密码:<INPUT TYPE="password" name="pwd"><br/> 
<INPUT TYPE="submit" value="提交"> 
</FORM> 
</body> 
</html>

login.php

The code is as follows:

<?php 
global $login; 
if ($_POST[&#39;name&#39;]!="Victor" || $_POST[&#39;pwd&#39;]!="111111") 
{ 
        echo "登陆失败"; 
        echo "请<a href=index.htm>返回</a>"; 
        exit; 
} 
$login = array(&#39;name&#39;=>$_POST[&#39;name&#39;], 
                           &#39;pwd&#39;=>$_POST[&#39;pwd&#39;]); 
session_start(); 
session_register(login); 
echo "<a href=info.php>查看信息</a><br/>"; 
echo "<a href=logout.php>退出登陆</a><br/>"; 
?>

info.php

The code is as follows:

<?php 
session_start(); 
if (session_is_registered(login)) 
{ 
        global $login; 
        echo "hello,".$login[&#39;name&#39;]."<br/>"; 
        echo "<a href=logout.php>退出登陆</a><br/>"; 
} 
else 
{ 
        echo "非法操作<br/>"; 
        exit; 
} 
?>

logout.php

The code is as follows:

<?php 
session_start(); 
session_unregister(login); 
header("location:index.htm"); 
?>

The above is the detailed content of Detailed explanation of how to use php Session variables. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 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: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.