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 Source insight编写代码后使用CCS5.2版本import之后,代码跳到注释行里面
  • ¥50 NT4.0系统 STOP:0X0000007B
  • ¥15 想问一下stata17中这段代码哪里有问题呀
  • ¥15 flink cdc无法实时同步mysql数据
  • ¥100 有人会搭建GPT-J-6B框架吗?有偿
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组