PHP 會話編碼解碼

Sheeraz Gul 2022年5月13日
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() 的字串形式。

Author: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook

相關文章 - PHP Encode