1

I am soon to be done on my website project and I am having a little trouble. Today I bought a web hosting server and a domain. Everything works perfectly on xampp on my localhost, but on the server the sessions seem to not work properly. I have no idea why. It presents to me with the error: Notice: Undefined variable: _SESSION

Although, the session does store something within it because it redirects me back to my main page when I try to go to the login page. It is right to do because there is an if in the start of the login page that does just that. It also destroys the contents of the session when I go to logout.php and lets me enter login.php when previously I couldn't without destroying it first.

I updated my site's php version to 7.3 and no luck so far. I am completely lost. I thought this question would have a lot of answers but none of the answers I've found online helped me.

This is the code of the login page:

<?php
// Initialize the session
session_start();

if(!empty($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true){
header("location: index.php");
exit;
}

// Include config file
require_once "config.php";

// Define variables and initialize with empty values
$username = $password = "";
$username_err = $password_err = "";

// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){

// Check if username is empty
if(empty(trim($_POST["username"]))){
    $username_err = "Please enter username.";
} else{
    $username = trim($_POST["username"]);
}

// Check if password is empty
if(empty(trim($_POST["password"]))){
    $password_err = "Please enter your password.";
} else{
    $password = trim($_POST["password"]);
}

// Validate credentials
if(empty($username_err) && empty($password_err)){
    // Prepare a select statement
    $sql = "SELECT id, username, password FROM accounts WHERE username = ?";

    if($stmt = mysqli_prepare($link, $sql)){
        // Bind variables to the prepared statement as parameters
        mysqli_stmt_bind_param($stmt, "s", $param_username);

        // Set parameters
        $param_username = $username;

        // Attempt to execute the prepared statement
        if(mysqli_stmt_execute($stmt)){
            // Store result
            mysqli_stmt_store_result($stmt);

            // Check if username exists, if yes then verify password
            if(mysqli_stmt_num_rows($stmt) == 1){                    
                // Bind result variables
                mysqli_stmt_bind_result($stmt, $id, $username, $hashed_password);
                if(mysqli_stmt_fetch($stmt)){
                    if(password_verify($password, $hashed_password)){
                        // Password is correct, so start a new session
                        session_start();

                        // Store data in session variables
                        $_SESSION["loggedin"] = true;
                        $_SESSION["id"] = $id;
                        $_SESSION["username"] = $username;                            

                        // Redirect user to welcome page
                        header("location: index.php");
                    } else{
                        // Display an error message if password is not valid
                        $password_err = "The password you entered was not valid.";
                    }
                }
            } else{
                // Display an error message if username doesn't exist
                $username_err = "No account found with that username.";
            }
        } else{
            echo "Oops! Something went wrong. Please try again later.";
        }
    }

    // Close statement
    mysqli_stmt_close($stmt);
}

// Close connection
mysqli_close($link);
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<center>
<meta charset="UTF-8">
<title>Login</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<style type="text/css">
    body{ font: 14px sans-serif; }
    .wrapper{ width: 350px; padding: 20px; }
</style>
</head>
<body>
<div class="wrapper">
    <h2>Login</h2>
    <p>Please fill in your credentials to login.</p>
    <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
        <div class="form-group <?php echo (!empty($username_err)) ? 'has-error' : ''; ?>">
            <label>Username</label>
            <input type="text" name="username" class="form-control" value="<?php echo $username; ?>">
            <span class="help-block"><?php echo $username_err; ?></span>
        </div>    
        <div class="form-group <?php echo (!empty($password_err)) ? 'has-error' : ''; ?>">
            <label>Password</label>
            <input type="password" name="password" class="form-control">
            <span class="help-block"><?php echo $password_err; ?></span>
        </div>
        <div class="form-group">
            <input type="submit" class="btn btn-primary" value="Login">
        </div>
        <p>Don't have an account? <a href="register.php">Sign up now</a>.</p>
    </form>
</div>    
</body>
</html>

Needless to say but the session is initialized in the page. I have only 1 page and it is the index.php. The session is initialized every time I use it - register.php, login.php, index.php. I also have a condition in the nav bar to present a special navigation option if the user is logged in.

 if(array_key_exists('loggedin', $_SESSION) && $_SESSION['loggedin'] == 1){
 echo "<script> document.getElementById('log').hide(); </script>";
 echo "<li id='out'><a href='logout.php'>Logout</a></li>";
 echo "<li id='cata' class='bg'><a href='catalog.php'><p class='colorinio thic'>Catalog (Wish Premium)</p></a></li>";
 }
 else{
 echo "<li id='log'><a href='login.php'>Login</a></li>";
 echo "<script> document.getElementById('out').hide(); </script>";
 echo "<script>document.getElementById('cata').hide(); </script>";
 }

This does not work although the session stores something. The register page functions great and the connection between the site and the sql server works flawlessly. I can insert users and it will tell me if the login is incorrect in the login page.

What could be the problem?

Sybrid
  • 63
  • 1
  • 9
  • why have you initialized ``session_start();`` in two places in your login page. Remove another one, except the one initialized at the top. Also you need to session_start(); in your index.php just after the PHP tag: `` – OMi Shah Nov 06 '19 at 18:10
  • 1
    Thanks for the tip. I already answered myself and realized how stupid I am. I would definitely remove the other session_start() since it can only cause confusion and errors. Thank you! – Sybrid Nov 06 '19 at 18:22

1 Answers1

1

I could have deleted this but I'd rather answer to myself and serve as a solution to future beginners in php instead of just deleting this resulting in complete waste of time. The solution is that I put

session_start();

after I started my HTML code. When I placed session_start(); at the head of the document everything worked just fine.

Thank you readers for reading, thank myself for...nothing.

Sybrid
  • 63
  • 1
  • 9