PHP - session_write_close() 函式



定義和用法

Session 或 session 處理是一種使資料在 Web 應用程式的各個頁面之間可用的方法。session_write_close() 函式儲存 session 資料(通常在指令碼終止後儲存)並結束 session。

語法

session_write_close();

引數

此函式不接受任何引數。

返回值

此函式返回一個布林值,成功時為 TRUE,失敗時為 FALSE。

PHP 版本

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

示例 1

以下示例演示了session_write_close() 函式的使用。

<html>   
   <head>
      <title>Setting up a PHP session</title>
   </head>   
   <body>
      <?php  	
         //Starting a session	  
         session_start();   
         //Replacing the old value
         $_SESSION["A"] = "Hello"; 	 
         print("Value of the session array: ");
         print_r($_SESSION);
         //Closing the session
         session_write_close();
         echo "<br>";
         print("Value: ".$_SESSION["A"]);
      ?>
   </body>   
</html> 

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

Value of the session array: Array ( [A] => Hello )
Value: Hello  

示例 2

以下是此函式的另一個示例,在此示例中,我們有兩個來自同一應用程式並在同一 session 中的頁面 -

session_page1.htm

<?php
   if(isset($_POST['SubmitButton'])){ 
      //Starting the session	
      session_start();
      $_SESSION['name'] = $_POST['name'];
      $_SESSION['age']  = $_POST['age']; 
      session_write_close();
      $_SESSION['test']  = "data";
   }
?>
<html>
   <body>
      <form action="#" method="post">
         <br>
         <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_page2.htm

<html>   
   <head>
      <title>Second Page</title>
   </head>
   <body>
      <?php
         //Session started
         session_start();	  
         print_r($_SESSION);
      ?>   
   </body>   
</html>

這將產生以下輸出 -

Array ( [city] => Hyderabad [phone] => 9848022338 [name] => krishna [age] => 30 )
php_function_reference.htm
廣告