Reputation: 354
I managed to develop a login page (index.php) which correctly redirects to another php page (welcome.php). My goal is to prevent users to access welcome.php page if not logged in.
I already followed suggestions of other users, here's part of code:
Index.php
<?php
include("settings/dbConfig.php");
if (!isset($_SESSION))
session_start();
if($_SESSION['login_user'])
header("location: php/welcome.php");
if($_SERVER["REQUEST_METHOD"] == "POST") {
// username and password sent from form
$myemail = mysqli_real_escape_string($db,$_POST['email']);
$mypassword = mysqli_real_escape_string($db,$_POST['pass']);
$sql = "SELECT id FROM users WHERE email = '$myemail' and password = md5('$mypassword');";
$result = mysqli_query($db, $sql);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$active = $row['active'];
$count = mysqli_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1
if($count == 1) {
$_SESSION['login_user'] = $myusername;
header("location: php/welcome.php");
}
else {
$error = "Login Failed... Please retry";
}
}
?>
Welcome.php
<?php
session_start();
if(!isset($_SESSION['login_user'])){
header("location: logout.php");
die();
}
?>
Login works good, if I try to access welcome.php page without having logged in I get immediately redirected to index.php page and that's good too.
Problem is: I get redirected to index.php even if I correctly log in with valid credentials.
I expect to be redirected back to index.php
only if I'm not logged in and to be redirected to welcome.php
if I'm logged in.
How should I modify provided code in order to achieve that?
Upvotes: 1
Views: 228
Reputation: 354
Managed to solve problem, was easier than expected.
Issue was on line : $_SESSION['login_user'] = $myusername;
Since $myusername
doesn't exists, of course session variable won't exist too.
Upvotes: 0
Reputation: 1960
try
<?php
session_start();
if(isset($_SESSION['login_user']))
header("location: php/welcome.php");
else
header("location: php/index.php");
?>
This might be a solution, but you better learn about prepared statements and PHP built-in functions for security reasons as suggested in comments.
Upvotes: 1