user3057533 user3057533 - 3 months ago 9
PHP Question

PHP sessions wont work? using variables on multiple pages

What i want i that i can use a variable to use on multiple pages.

The only problem is, is that it doesn't work cause i did something wrong i believe.

After a couple of hours looking at it thinking what could be wrong i decided to post it here, so maybe you can help me.

My code:
login.php:


<?php
if(empty($_SESSION['pass'])) {
echo "U bent niet ingelogt.";
echo '<form action="index2.php" method="post">';
echo 'Code <input type="text" name="code">';
echo '<input type="submit">';
echo '</form>';
} else {
redirect($url);
}

$url = "index2.php";
function redirect($url)
{
if (headers_sent()) {
die('<script type="text/javascript">window.location.href="' . $url . '";</script>');
} else {
header('Location: ' . $url);
die();
}
}
?>


Index2.php:


<?php
session_start();
// error_reporting(0);

$CODE = $_POST["code"];
$_SESSION["pass"] = $CODE;
if ($CODE == "testpassword") {
echo "password correct";
echo '<br /><a href="index.php">Index</a>';
} else {
echo "Password wrong";
echo '<br /><a href="login.php">Login</a>';
exit();
}
?>


Index.php:


<?php
session_start();
// error_reporting(0);

$CODE = $_POST["code"];
$_SESSION["pass"] = $CODE;
if ($CODE == "testpassword") {
echo "password correct";
} else {
echo "Password wrong";
exit();
}
?>

Answer

You need session_start() on each page that uses $_SESSION[] variables.

Missing in first file.

Comments