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 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答