search
HomeBackend DevelopmentPHP Tutorialphp创建session的方法实例详解_PHP

本文实例讲述了php创建session的方法。分享给大家供大家参考。具体分析如下:

保存session只需要两个步骤,开启session和保存session数据。默认情况下,session保存在服务器端 c:\windows\temp文件夹下(保存的路径可以在php.ini文件中修改:开启session.save_path,填写上保存的路径即可)。

session创建代码

代码如下:

echo "------如何保存 session 数据---------
";
//1、初始化 session
session_start();
//2、保存数据,可以保存的数据类型包括:字符串、整型、double型,数组,对象等
$_SESSION['name']="百度";//保存字符串
$_SESSION['age']=80;//保存整型

//保存数组
$arr = array("name"=>"小陈","age"=>25,"job"=>"程序员");
$_SESSION['person'] = $arr;

//保存对象
class Dog{
 public $name;
 public $age;
 public $color;
 function __construct($name,$age,$color){
  $this->name=$name;
  $this->age=$age;
  $this->color=$color;
 }
}
$dog = new Dog("小狗",2,"黄色");
$_SESSION['dog'] = $dog;

echo "保存成功";
?>


在C:\windows\temp文件下,找到一个保存session的文件,打开如下图:

说明:

(1)每一个session用分号;隔开。
(2)以第一个session为例:name表示键值、s表示字符串(相应:i表示整型,a表示数组,o表示对象等)、4表示长度、"百度"表示键值。

细节知识(很重要):

(1)每一个会话(就是打开浏览器访问某个网站,在关闭浏览器时,会话也就结束)对应一个session文件;
(2)session文件在执行 session_start()时创建,但此时,该文件为空,如果有session数据,则会写入该文件;
(3)session 数据默认保留时间为 1440秒,此时间为发呆时间,也就是在这段时间内,没有使用过该 session 文件(如果有使用过,那该文件的修改时间会自动更新--右键查看该文件属性即可看到)。可以在php.ini文件修改此默认值:session.gc_maxlifetime = 1440;
(4)重中之重:服务器在返回客户端浏览器请求时,会将session的信息( 如:PHPSESSID=0pk6fmamnk1btcgbcf444dnd76 ),以cookie的方式返回给浏览器(同样,你可以使用httpwatch来抓包查看)。当浏览器访问该网站的其它页面时,根据http协调,会把该cookie信息发送给服务器。服务器再根据该信息,查找到对应的session文件(对应的文件名为:sess_0pk6fmamnk1btcgbcf444dnd76)。

希望本文所述对大家的php程序设计有所帮助。

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
What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

PHP Email Security: Best Practices for Sending EmailsPHP Email Security: Best Practices for Sending EmailsMay 08, 2025 am 12:16 AM

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa

How do you optimize PHP applications for performance?How do you optimize PHP applications for performance?May 08, 2025 am 12:08 AM

TooptimizePHPapplicationsforperformance,usecaching,databaseoptimization,opcodecaching,andserverconfiguration.1)ImplementcachingwithAPCutoreducedatafetchtimes.2)Optimizedatabasesbyindexing,balancingreadandwriteoperations.3)EnableOPcachetoavoidrecompil

What is dependency injection in PHP?What is dependency injection in PHP?May 07, 2025 pm 03:09 PM

DependencyinjectioninPHPisadesignpatternthatenhancesflexibility,testability,andmaintainabilitybyprovidingexternaldependenciestoclasses.Itallowsforloosecoupling,easiertestingthroughmocking,andmodulardesign,butrequirescarefulstructuringtoavoidover-inje

Best PHP Performance Optimization TechniquesBest PHP Performance Optimization TechniquesMay 07, 2025 pm 03:05 PM

PHP performance optimization can be achieved through the following steps: 1) use require_once or include_once on the top of the script to reduce the number of file loads; 2) use preprocessing statements and batch processing to reduce the number of database queries; 3) configure OPcache for opcode cache; 4) enable and configure PHP-FPM optimization process management; 5) use CDN to distribute static resources; 6) use Xdebug or Blackfire for code performance analysis; 7) select efficient data structures such as arrays; 8) write modular code for optimization execution.

PHP Performance Optimization: Using Opcode CachingPHP Performance Optimization: Using Opcode CachingMay 07, 2025 pm 02:49 PM

OpcodecachingsignificantlyimprovesPHPperformancebycachingcompiledcode,reducingserverloadandresponsetimes.1)ItstorescompiledPHPcodeinmemory,bypassingparsingandcompiling.2)UseOPcachebysettingparametersinphp.ini,likememoryconsumptionandscriptlimits.3)Ad

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

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.