duandu6497 2019-04-11 12:06
浏览 54
已采纳

如果未设置会话,则PHP标头重定向不起作用

I'm trying to check if the user hasnt logged in on a cart.php, if they arent -redirect them to login.php.

This isn't working so I tried putting it in an elseif statement. If they are logged in and are on the cart page, redirect them to the cart page, and if they arent redirect them to the login page.

It is working in the sense that it redirects, yet if I login, it still redirects to login.php.

Also I'm not sure why none of the JS alerts are working.

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>';
}
  • 写回答

3条回答 默认 最新

  • duanbianweng5353 2019-04-11 14:29
    关注

    After a redirect you can't add more code, the new page will call and the script of the new one will run.

    You need somthing transfer from a page to another.

    Usually i use a cookie with a short time (2-5 seconds), the new page will call check if the cookie is set, if it is show the alert and unset the cookie.

    Here in the code you can see i put only an if statement (without else or else if) cause when the script fire the header location the next one code won't run and the new page will load.

    if (!isset($_SESSION['username'])){
        setcookie('notlogged', true, time() + 3;)
    
        header("Location: http://localhost/techiteasy/login.php");     
    }
    header("Location: http://localhost/techiteasy/cart.php");
    

    In the login.php

    if (isset($_COOKIE['notlogged']) && $_COOKIE['notlogged'] == true){
        echo '<script language="javascript">';
        echo 'alert("Please Login/Register")';
        echo '</script>';
    
        unset($_COOKIE['notlogged']);
    }
    

    Try this ;)

    You can also not set an expired time, it is just to avoid errors, but remind to unset every time, in other case the user only logs without passing from cart will wiew the alert.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥15 DruidDataSource一直closing
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据