From a login page I am capturing the user and password values:
<?php
session_start();
$error='';
$rows = 0;
if (isset($_POST['submit'])) {
$username=$_POST['username'];
$password=$_POST['password'];
$mysqli = new mysqli("localhost","xxxxx","xxxxx","xxxxxxx");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$username = stripslashes($username);
$password = stripslashes($password);
$username = $mysqli->real_escape_string($username);
$password = $mysqli->real_escape_string($password);
$query = "select count(*) from login where password='$password' AND username='$username'";
if ($stmt = $mysqli->prepare($query)) {
$stmt->execute();
$stmt->store_result();
$rows = $stmt->num_rows;
$stmt->close();
}
}
$mysqli->close();
if ($rows == 1) {
$_SESSION['login_user']=$username;
header("location: profile.php");
} else {
header("location: login.php");
$error = "Username or Password is invalid";
}
?>
My profile.php script is something like below:
<?php
include('session.php');
?>
<!DOCTYPE html>
<html>
<head>
<title>Your Home Page</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="profile">
<b id="welcome">Welcome : <i><?php echo $login_session; ?></i></b>
<b id="logout"><a href="logout.php">Log Out</a></b>
</div>
</body>
</html>
And session.php
<?php
if(!isset($_SESSION['login_user'])){
header('Location: login.php');
}
?>
My code flow is like when the login form is submitted the validate_login.php source code will verify the details from the user. In case the details are correct a profile.php page would be displayed or back again to login page.
I am having 3 difficulties;
- How to debug PHP scripts?
- Why my code is going back to login page again - I have tested by hard coding wrong undefined variable (forcing a dump) - I found that the row is found as it enters in if condition which defines the session variable [if ($rows == 1)]
- Is there any other way we can verify a session - basically only a logged in user should see the further pages?
session_start()insession.php