PHP - session_id() 函式



定義和用法

會話或會話處理是一種使資料在 Web 應用程式的各個頁面之間可用的一種方式。session_id() 函式用於設定或檢索當前會話的自定義 ID。

語法

session_id([$id]);

引數

序號 引數和描述
1

name(可選)

這是一個字串值,表示會話的 ID,如果您想使用此方法設定會話的 ID。

返回值

這將返回一個字串,表示當前會話的 ID(如果存在),或者如果當前會話沒有 ID,則返回一個空字串。

PHP 版本

此函式首次在 PHP 版本 4 中引入,並在所有後續版本中有效。

示例 1

以下示例演示了session_id() 函式的用法。

<html>   
   <head>
      <title>Setting up a PHP session</title>
   </head>   
   <body>
      <?php  
         //Starting the session
         session_start();   
         $id = session_id();
         print("Session Id: ".$id);
      ?>
   </body>   
</html>

執行上述 html 檔案後,它將顯示以下訊息:

Session Id: b9t3gprjtl35ms4sm937hj7s30

示例 2

以下是此函式的另一個示例,這裡我們在同一會話中具有來自同一應用程式的兩個頁面。

session_page1.htm

<?php
   if(isset($_POST['SubmitButton'])){ 
      //Starting the session	
      $id = session_create_id();	
      session_id($id);
      print("\n"."Id: ".$id);
      session_start();  
      $_SESSION['name'] = $_POST['name'];
      $_SESSION['age']  = $_POST['age'];	  
      session_commit();
   }
?>
<html>
   <body>
      <form action="#" method="post">
         <label for="fname">Enter the values click Submit and click on Next</label>
         <br><br><label for="fname">Name:</label>
         <input type="text" id="name" name="name"><br><br>
         <label for="lname">Age:</label>
         <input type="text" id="age" name="age"><br><br>           
         <input type="submit" name="SubmitButton"/>
         <?php 
            echo '<br><br /><a href="session_page2.htm">Next</a>';
         ?>
      </form>
   </body>
</html>

這將產生以下輸出:

Session Start

按下提交後,頁面將如下所示:

Session Create Id

點選下一個將執行以下檔案。

session_page2.htm

<html>   
   <head>
      <title>Second Page</title>
   </head>
   <body>
      <?php
         //Session started
         session_start();
         print("Values from the session with id: ".session_id());
         echo "<br>";
         print($_SESSION['name']); 
         echo "<br>";
         print($_SESSION['age']);
      ?>   
   </body>   
</html>

這將產生以下輸出:

Values from the session with id: brb9t3gprjtl35ms4sm937hj7s30
Krishna
30

示例 3

您可以使用此函式建立自定義會話 ID,如下所示:

<html>   
   <head>
      <title>Setting up a PHP session</title>
   </head>   
   <body>
      <?php  
         //Creating a custom session id
         session_id("my-id");
         //Starting the session
         session_start();   
         print("Id: ".session_id());
      ?>
   </body>   
</html> 

執行上述 html 檔案後,它將顯示以下訊息:

Id: my-id
php_function_reference.htm
廣告