doutong1890 2015-09-06 12:18
浏览 42
已采纳

通过$ _SESSION将变量传递到下一页

I need to pass a variable from login.php to index.php in order to get an error message if the user doesn't enter username or password. I have a modal form which pass $_POST['usename'] and $_POST['password'] to login.php.

login.php

require_once(realpath(__DIR__ . "/resources/session.php"));

if(!$logged) {
    if(isset($_POST['username']) && isset($_POST['password'])) {
        $username = mysqli_real_escape_string($conn, $_POST['username']);
        $password = mysqli_real_escape_string($conn, $_POST['password']);

        if(strlen($_POST['username']) == 0 || strlen($_POST['password']) == 0) {
            $_SESSION['noty'] = "error||topCenter||(here the message)";
            header("Location: index.php");
        } else {
            // Code...
        }
    }
} else {
    // Code ...
}

$_SESSION['noty'] is the variable that I should pass to index.php.

index.php

$page_id = 1;
require_once(realpath(__DIR__ . "/resources/session.php"));

require_once(TEMPLATE_PATH . "/header.php");
require_once(TEMPLATE_PATH . "/sidebar.php");
require_once(TEMPLATE_PATH . "/breadcrumb.php");

renderLayout(VIEWS_PATH . "/index.view.php");

require_once(TEMPLATE_PATH . "/footer.php");

and at the bottom of the header.php which is included on index.php:

if(isset($_SESSION['noty']) AND strlen($_SESSION['noty']) > 0) {
    $noty = explode("||", $_SESSION['noty']);
    noty($noty[2], $noty[1], $noty[0]);
    $_SESSION['noty'] = "";
} else {
    $_SESSION['noty'] = "";
}

Also noty function is:

function noty($text, $layout, $type) {
    echo "<script type=\"text/javascript\">
        noty({text: '$text', layout: '$layout', type: '$type'});
        </script>";
}

This isn't working. $_SESSION['noty'] is not set when I get to index.php from login.php.

EDIT 1:

session.php contains session_start() on top and it is required on both index.php and login.php.

EDIT 2:

exit; after header() redirect doesn't works for me.

SOLVED:

I set $_SESSION to array() whenever a user wasn't logged in on session.php, so it was deleting also $_SESSION['noty']. That error was so stupid.

  • 写回答

1条回答 默认 最新

  • douchen7324 2015-09-06 14:42
    关注

    After using header() function, you shall use exit; function. More details: PHP session destroyed / lost after header

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?