HOWTO · PHP

PHP 会话编码解码

本教程演示了如何在 PHP 中对会话进行编码和解码。

本页内容

在 PHP 中,会话是一种跨网页处理数据的方式。会话编码和解码操作是存储或读取会话数据时的要求。

在 PHP 中演示使用 session_encode()session_decode

内置函数 session_encode()$_SESSION 数组数据序列化为字符串,然后 session_decode() 再次将会话数据转换为真实格式。

我们通过表单插入数据,然后将其存储到会话中:

test.php

<html>
<head>
<title> Demonstration of Session </title>
</head>
<body>
<form action="action.php" method="post" >
<div style="border: 4px solid;padding:10px; width:40%">
Employee Name:<input type="text" name="employee">
ID:<input type="text"  name="id">
<input type="submit" value="SUBMIT" name="submit">
</div>
</form>
</body>
</html>

会话像 cookie 一样工作;一旦我们启动会话并开始存储数据,我们就可以使用它直到会话被销毁。

输出:

PHP 会话编码和解码

编码的会话字符串包含由 ; 分隔的所有会话元素。这里应该提到的是,这种序列化与 PHP serialize() 不同。

action.php

<?php
if (isset($_POST['submit']))
{
    // Start the Session
    session_start();
    //Form Data
    $employee=$_POST['employee'];
    $id=$_POST['id'];
    //store the form data into session
    $_SESSION['employee']=$employee;
    $_SESSION['id']=$id;

    echo "According to the data from session: <br>";
    echo "Hello ". $employee. "! your ID is ".$id."<br><br>";

    echo"The encoded Session Data is: <br>";
	//encode the session
    $session_econded= session_encode();
    echo $session_econded."<br><br>";
	//decode session
    session_decode($session_econded);
    echo "Session data after decode: ";
    print_r( $_SESSION);
	//Destroy the Session
    session_destroy();
}
?>

输出:

According to the data from session:
Hello Jack! your ID is 1234

The encoded Session Data is:
employee|s:4:"Jack";id|s:4:"1234";

Session data after decode: Array ( [employee] => Jack [id] => 1234 ) 

编码数据采用类似于 PHP serialize() 的字符串形式。