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 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码