2012-07-11 16 views
2

使用PHP的會話我一直在使用這種代碼在我的網頁一個問題:PHP:「該網站重定向過多」時,隨着時間的推移

代碼到期會議

<?php 
session_start(); 
if(!isset($_SESSION['clientmacs'])) { 
    header('Location: index.php'); 
} else { 
    if(time() - $_SESSION['timeLogin'] > 1800) { 
     header('Location: include/logout.php'); 
    } 
    $userclient = $_SESSION['clientmacs']; 
?> 
<html> 
    HTML CODE 
</html> 
<?php 
} 
?> 

但如果我使用此代碼的問題消失,頁面正常工作:

代碼而不終止會話

<?php 
session_start(); 
if(!isset($_SESSION['clientmacs'])) { 
    header('Location: index.php'); 
} else { 
    $userclient = $_SESSION['client'];; 
?> 
<html> 
    HTML CODE 
</html> 
<?php 
} 
?> 

錯誤谷歌瀏覽器:

This webpage has a redirect loop 

Http://localhost/mac/index.php The website has too many redirects. The incidence may be 
resolved by deleting the cookies from this site or allowing third party cookies. If 
that fails, the incidence may be related to a bug in the server configuration, not the 
computer. 

回答

4

當您執行重定向時,您需要重置$ _SESSION值超時($ _SESSION ['timeLogin']),否則當客戶端返回重定向時,session中的值將相同,並且將被重定向。

您可以用解決它:

if(!isset($_SESSION['clientmacs'])) { 
    $_SESSION['clientmacs'] = ""; // add this line if not added somewhere else 
    header('Location: index.php'); 
} 

if(time() - $_SESSION['timeLogin'] > 1800) { 
    $_SESSION['timeLogin'] = time(); // add this line 
    header('Location: include/logout.php'); 
} 

也許(這取決於你的邏輯)被更好地清除整個會話,並讓它通過正常流程進行重新配置(session_destroy() )當你執行重定向。

+0

適合我和@Ibu的回答! – SoldierCorp 2012-07-11 21:35:12

2

這裏是你需要添加

if(!isset($_SESSION['clientmacs'])) { 
    $_SESSION['clientmacs'] = 'something' // or it will redirect forever; 
    header('Location: index.php'); 
} 
+0

會話名稱在其他PHP文件中加入! – SoldierCorp 2012-07-11 21:22:50

+0

@SoldierCorp你將不得不再次檢查,因爲這是什麼導致你的無限重定向 – Ibu 2012-07-11 21:23:46

+0

適合我和@Francisco Spaeth! :/ – SoldierCorp 2012-07-11 21:35:27

1

你註銷被重定向到您的索引,它會再次檢查條件

什麼

if(time() - $_SESSION['timeLogin'] > 1800)

這將是真實的,並將它發送回註銷,等等等等。你需要改變你的$ _SESSION ['timeLogin'],否則你永遠不會打破這個循環。

0

嘗試計算IF語句之外的時間差。

e.g

$difference = time() - $_SESSION['timeLogin']; 

if($difference > 1800){ 
    //Do Something 
} 
相關問題