[英]PHP header redirect not working if the session isnt set
我正在嘗試檢查用戶是否沒有登錄cart.php,如果他們沒有登錄-將他們重定向到login.php。
這不起作用,所以我嘗試將其放入 elseif 語句中。 如果他們已登錄並在購物車頁面上,則將他們重定向到購物車頁面,如果他們沒有將他們重定向到登錄頁面。
它在重定向的意義上起作用,但如果我登錄,它仍然重定向到 login.php。
此外,我不確定為什么 JS 警報都不起作用。
if (isset($_SESSION['username'])){
header("Location: http://localhost/techiteasy/cart.php");
}
else if (!isset($_SESSION['username'])){
header("Location: http://localhost/techiteasy/login.php");
echo '<script language="javascript">';
echo 'alert("Please Login/Register")';
echo '</script>';
}
您可以簡單地使用如下。 不需要再次檢查否定條件。 只需使用 if-else。
if (isset($_SESSION['username'])){
header("Location: http://localhost/techiteasy/cart.php");
}
else{
header("Location: http://localhost/techiteasy/login.php");
echo '<script language="javascript">';
echo 'alert("Please Login/Register")';
echo '</script>';
}
重定向后,您無法添加更多代碼,新頁面將調用並運行新頁面的腳本。
你需要從一個頁面轉移到另一個頁面。
通常我使用短時間(2-5 秒)的 cookie,新頁面將調用檢查是否設置了 cookie,如果顯示警報並取消設置 cookie。
在代碼中,您可以看到我只放置了一個 if 語句(沒有 else 或 else if),原因是當腳本觸發標頭位置時,下一個代碼將不會運行並且新頁面將加載。
if (!isset($_SESSION['username'])){
setcookie('notlogged', true, time() + 3;)
header("Location: http://localhost/techiteasy/login.php");
}
header("Location: http://localhost/techiteasy/cart.php");
在登錄.php
if (isset($_COOKIE['notlogged']) && $_COOKIE['notlogged'] == true){
echo '<script language="javascript">';
echo 'alert("Please Login/Register")';
echo '</script>';
unset($_COOKIE['notlogged']);
}
嘗試這個 ;)
也可以不設置過期時間,只是為了避免出錯,但每次都提醒取消設置,否則用戶只登錄而不從購物車中通過就會看到警報。
在 PHP5 上試試這個
if(isset($_SESSION['username'])){ header("Location: http://localhost/techiteasy/cart.php");
}
else{
if(!isset($_SESSION['username'])){
echo '<script>alert("Login with vaild user and pass");</script>';
header("Location: http://localhost/techiteasy/login.php");
exit;
}}
對於 PHP7
if(isset($_SESSION['username'])){ header("Location: http://localhost/techiteasy/cart.php, true, 301");
}
else{
if(!isset($_SESSION['username'])){
echo '<script>alert("Login with vaild user and pass");</script>';
header("Location: http://localhost/techiteasy/login.php, true, 301");
exit;
}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.