0

I want to pass session variable from login.php page to test-start.php

My PHP login page:

<?php session_start();?>
<html>
<body>
<?php 
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if ($_POST["username"] == "suren" && $_POST["password"] == "passwd")
{
$_SESSION['login'] = true;
$_SESSION["var"]="true";
var_dump($_SESSION['login']);
header("location: /login/test-start.php");
#session_write_close()
#I've tried session_write_close option as well!!!
exit();
}
else 
{
echo "<h2>Try Again !!!</h2>";
}
}
?>
<form method = "POST" action = "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<input type = "text" name="username">
<input type = "text" name = "password">
<input type="submit" value = "login">
</form>
</body>
</html>

My second page:

<?php session_start();?>
<html>
<body>
<?php
var_dump($_SESSION['login']);
echo $_SESSION['login'];
if (!$_SESSION['login']){
echo "<h2>Login first!!!<h2>";
#header("location:/login/newlogin.php");
#die;
}
#echo "<h2>Successfully Logged in <h2>";
?>
</body>
</html>

And here I'm getting the below output: I used var_dump() for the session variable...

/opt/monitor/web/login/test-start.php:6:null

Login first!!!

Touheed Khan
  • 2,149
  • 16
  • 26
Suren
  • 37
  • 7

1 Answers1

0

I am unable to reproduce your code. It works fine here. The second script reports that the login was successful. However, you have output before redirecting with the header command, which can lead to some problems. I have just slightly adjusted your code, but kept your implementation:

newlogin.php

<?php 
session_start();
$try_again = false;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if ($_POST["username"] == "suren" && $_POST["password"] == "passwd") {
        $_SESSION['login'] = true;
        $_SESSION["var"]="true";
        header("location: loggedin.php");
        exit();
    }
    else {
        $try_again = true;
    }
}
?>
<html>
<body>
<?php
if ($try_again) { 
    echo "<h2>Try Again !!!</h2>";
}
?>
<form method = "POST" action = "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<input type = "text" name="username">
<input type = "text" name = "password">
<input type="submit" value = "login">
</form>
</body>
</html>

loggedin.php

<?php 
session_start();
var_dump($_SESSION);

Output

array(2) { ["login"]=> bool(true) ["var"]=> string(4) "true" }

Edit: It could be possible that you have encoded your files as UTF8 with BOM. This inserts an invisible character at the beginning of each file. This leads to session_start failing. If you have turned off all error outputting you might not see this error. Try encoding your file as UTF8 without BOM if you have not already done this.

OptimusCrime
  • 14,662
  • 13
  • 58
  • 96