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 本地测试网站127.0.0.1 已拒绝连接,如何解决?(标签-ubuntu)
  • ¥50 Qt在release捕获异常并跟踪堆栈(有Demo,跑一下环境再回答)
  • ¥30 python,LLM 文本提炼
  • ¥15 关于将inet引入的相关问题
  • ¥15 关于一个倒计时的操作和显示设计
  • ¥15 提问STK的问题,哪位航天领域的同学会啊
  • ¥15 苹果系统的mac m1芯片的笔记本使用ce修改器使用不了
  • ¥15 单相逆变的电压电流双闭环中进行低通滤波PID算法改进
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 如何卸载arcgis 10.1 data reviewer for desktop