2017-04-09 63 views
0

我有一個php網頁,可以在用戶閒置10秒後將用戶註銷。 10秒後,我需要點擊刷新按鈕,然後重定向到主index.php頁面。我如何使一個彈出框顯示「由於不活動而退出」,然後重定向到index.php而不刷新? P/S:我是學習基礎知識的學生,所以我不太瞭解。在會話超時觸發前顯示一條消息

session_start(); 

$timeout = 10; 
// Check if the timeout field exists. 
if(isset($_SESSION['timeout'])) { 
// See if the number of seconds since the last 
// visit is larger than the timeout period. 
$duration = time() - (int)$_SESSION['timeout']; 
if($duration > $timeout) { 
// Destroy the session and restart it. 
session_destroy(); 
session_start(); 
} 
} 

So I tried something like this using alert.Why doesn't it work? 
<?php 
//include ("popup.php"); 
session_start(); 

$timeout = 10; 
// Check if the timeout field exists. 
if(isset($_SESSION['timeout'])) { 
// See if the number of seconds since the last 
// visit is larger than the timeout period. 
$duration = time() - (int)$_SESSION['timeout']; 
if($duration > $timeout) { 
echo"<script type='javascript'>alert('10 seconds over!'); 
header("location:../../index.php"); 
</script>"; 

} 
// Destroy the session and restart it. 
session_destroy(); 
session_start(); 
header("location:../../index.php"); 
} 


// Update the timout field with the current time. 
$_SESSION['timeout'] = time(); 
+2

你不能用PHP做到這一點,但它不會太容易使用Javascript添加。但是,我可以確認您在轉發到index.php之前不要顯示您的警報嗎?在你的重定向之後做這件事情沒有什麼意義,所以如果有人在不同的網站/類似網站上,他們仍然會看到「已註銷」通知?如果您在重定向之前想要通知,我可以爲您解決。 –

+0

我想要一個類似於「你已經被註銷,因爲不活動」的彈出框,並有一個Ok/some按鈕,當你點擊它後,它會重定向到index.php。 –

回答

0
  1. 實現與JavaScript中的彈出;或
  2. 在你的條件,使用header("Location: logout-notice.php");

編輯: 我現在不能測試,但基於您的更新,我看到的東西是,你檢查$ _SESSION [「超時」 ]但我沒有看到它在任何地方宣佈或給定價值。您可以在頂部設置$ timeout變量,但它們是不同的變量。

也許是這樣的:

$_SESSION['timeout'] = time() + $timeout; // should = 1491838370 if set at UNIX time of 1491838360 
if(time() > $_SESSION['timeout']){ // evaluated at 1491838380 which is > 1491838370 results in true 
    ?> 
    <script type='javascript'>alert('10 seconds over!');</script> 
    <?php 
    header("Location: ../../index.php"); 
} 

的問題是在哪裏/你怎麼會評估此。如果您希望每個用戶的操作驗證它們是否處於活動狀態,則可以在每個文件的開頭包含此腳本。缺點是如果他們暫時不活躍,那麼他們不會評估,直到他們做了一些事情。

您可以使用純粹的JavaScript版本依靠SetIntervalSetTimeout來評估每隔10秒鐘,並彈出一個警報,並將window.location.href也彈出到index.php中。像這樣的東西(你可能需要調整,這是未經測試):

var checkSession = setInterval(
    function({ 
     var sessionExpires = <?=$_SESSION['timeout']?>; //this is probably considered heresy, but as long as the javascript is evaluated by the PHP processor, it should work 
     var currentTime = Math.floor((new Date).getTime()/1000); 
     if(currentTime > sessionExpires){ 
       alert("Take your stuff and go!"); 
       window.location.href = "../../index.php"; 
     } 
    }, 10000); 
相關問題