1

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.

reyy
  • 69
  • 9

1 Answers1

0

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

Community
  • 1
  • 1
Grzegorz Gajda
  • 2,424
  • 2
  • 15
  • 23
  • Thanks for your answer but it doesn't work for me. `$_SESSION['noty']` is still unset on **index.php**. – reyy Sep 06 '15 at 15:05