PHP - session_start() 函式



定義和用法

會話或會話處理是一種使資料在 Web 應用程式的各個頁面之間可用的方法。session_start() 函式用於啟動新會話或恢復現有會話。

語法

session_start([$options]);

引數

序號 引數 & 說明
1

陣列(可選)

這是一個表示一組會話選項的陣列。

返回值

此函式返回一個布林值,如果會話成功啟動則為 TRUE,否則為 FALSE

PHP 版本

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

示例 1

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

<?php
   //Starting the session
   session_start();   
   if( isset( $_SESSION['counter'] ) ) {
      $_SESSION['counter'] += 1;
   } else {
      $_SESSION['counter'] = 1;
   }	
   $msg = "You have visited this page ". $_SESSION['counter'];
   $msg .= "in this session.";
?>
<html>  
   <head>
      <title>Setting up a PHP session</title>
   </head>   
   <body>
      <?php  echo ( $msg ); ?>
   </body>    
</html>  

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

You have visited this page 1 times in this session.

訊息中的數字會根據您在不關閉瀏覽器的情況下重新整理頁面的次數而不斷變化。例如,如果您重新整理 10 次,則同一頁面會顯示以下訊息。

You have visited this page 16 times in this session.

示例 2

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

session_page1.htm

<?php
   if(isset($_POST['SubmitButton'])){ 
      //Starting the session	
      session_start();
      $_SESSION['name'] = $_POST['name'];
      $_SESSION['age']  = $_POST['age'];
   }
?>
<html>
   <body>
      <form action="#" method="post">
         <br?> <label for="fname">Enter the values click Submit and click on Next</label?> <label for="fname"?>Name:</label>
         <input type="text" id="name" name="name"><br><br>
         <label for="lname"?>Age:
         <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($_SESSION['name']); 
         echo "<br>";
         print($_SESSION['age']);
      ?>   
   </body>   
</html>

這將產生以下輸出:

Krishna
30

示例 3

您可以像下面這樣將可選陣列傳遞給此函式:

<html>   
   <head>
      <title>Setting up a PHP session</title>
   </head>   
   <body>
      <?php
         //Starting the session
         $options = ['cookie_lifetime' => 86400,'read_and_close'  => true];
         session_start($options);   
      ?>  
   </body>   
</html>
php_function_reference.htm
廣告