I was created simple login and register system and have some issue. But not sure is it with cookie or cookie and php. My code is next:
On index.php ( login page i have this code in header ):
<?php
include('includes/config.php');
if(!$user->is_logged_in()){
header('Location: index.php');
exit;
}
if(isset($_POST['submit'])){
$username = $_POST['username'];
$password = $_POST['password'];
if($user->login($username,$password)){
$_SESSION['username'] = $username;
header('Location: home.php');
exit;
} else {
$error[] = 'Wrong username or password or your account has not been activated.';
}
}
?>
And on home page when user is successfully logged in:
<?php include('includes/config.php');
if(!$user->is_logged_in()){
header('Location: index.php');
exit;
}
?>
Config file:
<?php
ob_start();
session_start();
date_default_timezone_set('Europe/London');
define('DBHOST','localhost');
define('DBUSER','root');
define('DBPASS','pass');
define('DBNAME','db_name');
define('DIR','http://example.com/');
define('SITEEMAIL','noreply@domain.com');
try {
$db = new PDO("mysql:host=".DBHOST.";dbname=".DBNAME, DBUSER, DBPASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo '<p class="bg-danger">'.$e->getMessage().'</p>';
exit;
}
include('classes/user.php');
include('classes/phpmailer/mail.php');
$user = new User($db);
?>
Problem is next, when user successfully logged in and redirected to home page, when user is log out everything is fine, but when user logged in and without log out go back to index page ( log in page ) i get this error:
This page isn’t working website.com redirected you too many times. Try clearing your cookies. ERR_TOO_MANY_REDIRECTS
And when i clear my cookie from google chrome browser, error is fixed but user must login again and when same step do again i get again same error.
You should break this up into three scripts, with the following logic:
Home page (and all other content pages): If they're not logged in, it redirects to the login page.
Login page: If they're already logged in, redirect to the home page.
Password checker: This is the action of the login form on the login page. It checks the username and password. If they're correct, it sets the session variable that says that the user is logged in, and redirects to home page. If they're not correct, it redirects back to the login page.
Problem was on index page ( login page ):
OLD code
if( $user->is_logged_in()){
header('Location: index.php'); --> THIS IS WHERE PROBLEM IS
}
NEW code
if( $user->is_logged_in()){
header('Location: home.php'); // Work correctly
}