Reputation: 25
I have been messing with this for a while and I know it is something simple. I have used essentially the same code on another website and it doesn't appear to have any problems and is running on the same server so I don't think it is a server-side issue. This is a very simple login script:
function user_login($username, $password) {
$passcorrect = user_checkpass($username, $password);
if ($passcorrect == "1") {
$_SESSION['eocname'] = $username;
echo("SETTING SESSION: ".$_SESSION['eocname']."<br />");
$success = "1";
} else {
$success = "0";
}
return($success);
}
This does appear to be setting the SESSION variable and is in the functions.php file.
However, once you refresh the page, the SESSION appears to disappear. Here is the code on the page.php file:
<?php
if (!isset($_SESSION['eocname'])) {
if (!isset($_POST['username'])) {
echo("You must login to access this page!");
echo($_SESSION['username']);
} else {
$result = user_login($_POST['username'], $_POST['password']);
if ($result == "0") {
echo("Incorrect Username or Password.");
} else {
echo("Login Successful!");
}
}
} else {
echo('Welcome back, '.$_SESSION['username'].'!');
}
?>
Please note that I do realize there may be some redundant things in there, I've been toying with it trying to determine the problem, but it seems that everytime $_SESSION['eocname'] does not appear to have been set once the page is refreshed.
I have added session_start(); to the top of my functions.php file without error to ensure that it would work, but still no luck.
Upvotes: 0
Views: 3759
Reputation: 914
You should create a init action in your plugin and start the session inside the function init. Your code should look like:
add_action('init', 'initEverything');
function initEverything() {
if(!session_id()) {
session_start();
}
}
Other option is start the session in wp-config.php
if(!session_id()) {
session_start();
}
Upvotes: 1