I’m having a little issue with some php logic in my main index page, that will include certain pages based on the results of some functions, mainly to do with login/logout and the first time a user logs in after registering. The php that manages the includes is below:
UPDATE: (Based on suggestions from @arjan and @bigman I’ve updated the code as follows. The end result is still the same).
<?php
if ($login->checkForRegisterPage()) {
include("views/pages/home.php");
// are we logged in ?
} elseif ($login->isLoggedIn()) {
// check whether account is activated
if (!$login->checkActivated()) {
include("views/pages/activate.php");
// check whether user has logged in before
} elseif ($login->checkFirstLogin()) {
include("views/pages/build_profile.php");
// check action in URL and redirect accordingly
} elseif ($checkaction->checkForBuildProfilePage()) {
include("views/pages/build_profile.php");
} elseif ($checkaction->checkForViewProfilePage()) {
include("views/pages/profile.php");
// if all else fails, load the dashboard
} else {
include("views/pages/dashboard.php");
}
} else {
// not logged in, showing the login form
include("views/pages/home.php");
}
?>
The problem is with the two functions $login->checkActivated(); and $login->checkFirstLogin(); included below:
public function checkFirstLogin() {
$checkfirstlogin = $this->db->query("SELECT first_login FROM users WHERE first_login = 'Y' AND user_name = '".$this->user_name."';");
if($checkfirstlogin->num_rows == 1) {
return true;
} else {
return false;
}
}
public function checkActivated() {
$checkactivated = $this->db->query("SELECT activated FROM users WHERE activated = 'N' AND user_name = '".$this->user_name."';");
if($checkactivated->num_rows == 1) {
return false;
} else {
return true;
}
}
When the user first logs in, these functions return the correct result and I receive the page that I want. However, after login, I can still click and travel to other links on the page e.g. checkForViewProfilePage(); looks for view=profile in the URL. The thing is in order for the logic to reach the point where it even checks for that, it would have had to get past the two functions checkActivate(); and checkFirstLogin();, which it shouldn’t be able to do while those criteria are met, but it still can. I hope I’m making sense. Can anyone see an error?
Obviously my login form calls the Login class which the awkward functions are stored in, and so this would be loaded on login, but the class is included in the same way here so I’m not sure why the functions don’t appear to be firing.
I solved it. The problem was higher up in the Login class – in Login db connections are only created when a session_start() is fired, i.e. on first login. Created a new class with db connection launched with each function and everything worked as it was.
Thanks to @arjan and @bigman for the formatting tips r.e. nesting.