0
votes

I am getting some unexpected errors on some code which has been working for a few weeks. I haven't changed this code yet I'm getting two errors upon logging in.

session_name(): Cannot change session name when session is active in /opt/lampp/htdocs/FantasyKicks/index.php on line 5

session_start(): A session had already been started - ignoring in /opt/lampp/htdocs/FantasyKicks/index.php on line 7

I have tried running session_destroy() to put me back on the login page and delete the session and then taking that line out and logging back in, but both errors still appears. I am wondering if there is actually an issue with how I've coded the logging in process or not.

login.php (i've taken out some irrelevant code on this page)

session_name('FantasyKicks');

session_start();

if(!$email & !$password) {
        echo "All fields required";
    } else {
        if(!$email) {
            echo "Email required";
        } else {
            if(!$password) {
                echo "Password required";
            } else {
                if($num == 0) {
                    echo "Incorrect email or password";
                } else {
                    // User is logged in
                    echo "LoggedIn";
                    $_SESSION['UserID'] = $user['UserID'];
                    $_SESSION['Email'] = $user['Email'];
                    $_SESSION['FirstName'] = $user['FirstName'];
                    $_SESSION['LastName'] = $user['LastName'];
                    $_SESSION['logged_in'] = true;
                }
            }
        }
    }

index.php (start of index.php)

require 'fkdb.php'; // Connect to database which uses XML config file

session_name('FantasyKicks');

session_start();
if (!isset($_SESSION['logged_in'])) {
   $_SESSION['logged_in'] = false;
};
1

1 Answers

0
votes

You are calling the session methods excessively, you should only use session_start(); once at the top of your code in a controller. If you really have to check if the session is started you can use the code below, but it is best practice to call it once.

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

If you are calling it once and it still fails it could be your php configuration. In php.ini find the following line and set it to false:

session.auto_start = false

As for the session name, this is just the name of the cookie; session_name(); is functionally equivalent to ini_get('session.name'); so unless you want to change the php configuration, I do not see why you would want to call this method. I would keep the default 'PHPSESSID' as it makes debugging easier.