Using session variables to keep user logged in if they havent logged out

I have moved onto PHP and was designing a register and login system that would allow the user whos username and password is stored in the database to access the Members page.

I have set up the register and login page with validation that was needed but i have one small problem.
When i log in using the username and password i am redirected to the members page.

I want the script of my login and member page to use session variables that would keep the user logged in unless they press logout on the member page. Can you please help me.

This is the code for the login and member page.

Login page:

<!DOCTYPE html>

<html lang="en">
	<head>
		<!--title of the web page-->
		<title>Login - Mas Agency</title>
		
		<!--web page meta tags-->
		<meta charset="utf-8" />
		
		<!--specific web page meta tags-->
		
		
		<!--CSS Links-->
		<link rel="stylesheet" type="text/css" href="style.css">
		
		
	</head>
<body>

<!--Register users-->

<form name="register" method="post" 
	action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" >
	
	
	<strong> Register Account</strong> <br /><br /> 
	
		
	User name:
		<input type="text" name="username"><br /><br />
	
	Password:
		<input type="text" name="password"><br /><br />
	
		<br /><br />
		<input type = "submit" value = "register" / >
		
	
</form>

<?php

session_start();

//validate registration form

if ( (empty($_POST['username'])) OR (empty($_POST['password'])) )
{
	//if the values are empty - 
	
	echo "<br /> Please fill in all the above inputs";

	}else{
		echo "<br> Process Validation";
		//if the inputs has values
	
		//store the data into local variables
	
		$Username = $_POST['username'];
		$Password = $_POST['password'];
	
		$Check=true;
		
		//Validate password - has to be more than 5 char
		if (strlen($Username) <5 )
		{
			echo "<br> Username or Password is incorrect";
			$Check=false;
		}
	
		//if first name has any special characters
		if (is_numeric($Username))
		{
			echo "<br> error - username has number...";
			$Check=false;
		}
	
		//if username is email format
	
		// Variable to check

		// Validate email
		if(filter_var($_POST['username'],FILTER_VALIDATE_EMAIL)){
		}
		else{
			echo '<br>Invalid email format';
			$Check=false;
		}
	
		//all the password validations
	
		if (strlen($Password) <5 )
		{
			echo "<br> error - password has less than 5 characters";
			$Check=false;
		}
	
		//if all the validation are true then prepare
	
		//to store to online database
		if ($Check == true)
		{
		echo "<br> Checking.....";
		
		require_once('db.php'); //connect the database
		
		$SQL = "SELECT * FROM user WHERE username='$Username' and password='$Password'";
		
		$result = $conn->query($SQL); //execute the SQL query and store the data in $result as an array
		
		if ($result->num_rows>0)
		{
			$_SESSION['username'] = $username;
			//user information available in database
			echo "Login successful";
			echo "<br><br> re-directing to members page";
			header ( 'refresh:5; url=member.php?id='.$Username ); //re-directing to member page
		}
		else{
			//users info not found
			echo "<br> Username or Password incorrect";
		if(isset($_GET['logout'])){
			session_unregister('username');
		}
	}
	
	
}
	
	
	
}

?>


</body>
</html>

Member page:

<?php

session_start();

if ((empty($_GET['id'])) )
{
	//if the values passed is empty -
	
	if(!isset($_SESSION['username']))
{
	header("location:login.php");
}
	//redirect to login page after 5 seconds
	
	}
	else
		
	{
	echo "<br> -------- Hello --------<br><br>";
	
	
	//local variables
	
	$Username = $_GET['id'];
	
	require_once('db.php'); //connect the database
		
		$SQL = "SELECT * FROM user WHERE username='$Username'";
		
		$result = $conn->query($SQL); //execute the SQL query and store the data in $result as an array
		
		
		
		if ($result->num_rows>0)
		{
			
			//loop through the $result array and display the data
			
		while($row = $result->fetch_assoc()) 
		{
			echo "<br>".$row['fname']." ".$row['sname'];
			echo '<br><a href="login.php?action=logout">Logout</a>';
			
		}
		
		}
		else
	{
		echo "can not open members page",
		session_destroy();
	}
	
}
	
?>

Before you get into sessions, I need to point out that this whole system is fantastically insecure and needs a re-think.
Not sure where to start…
Here’s one for you.
What happens if you bypass the login page and go directly to the member page by manually typing in the url and a user id?
There’s more…

A few more key points, though maybe too many to mention.
Getting back to the login form/script.
If you are going to put your form processing in the same file as your html form, put the processing first.
Things like headers and session_start should be done before any output to the browser.
To avoid the script running any time the page is viewed (as in when filling out the form) test the request method like this:-

<?php
if($_SERVER['REQUEST_METHOD'] === 'POST'){
    // Form processing here...
}
?>
<!DOCTYPE html>
etc...

This part:-

if(filter_var($_POST['username'],FILTER_VALIDATE_EMAIL)){

…tells me you expect a valid email address as the username. That’'s fine, but if you are using this function, it makes the previous “validation” you did on the username redundant.

$SQL = "SELECT * FROM user WHERE username='$Username' and password='$Password'";

This part has some serious no-nos.
Never store unhashed passwords. In the sign-up script you should hash the input with password_hash and put the hash into the database.
Also never put variables directly into a query like this, it is wide open to exploitation by SQL injection. The user could put absolutely anything into those form fields. Use prepared statements instead.

1 Like

You beter check this login script for an example

Im trying to create a login system that creates a session if the user logs in to the member page. Once in the member page they can press logout to end the session otherwise if they dont, whenever they open up the login page they are redirected to the member page with their details displayed as if they have just logged in again.

How can i do this?

So far ive got this to create the session:

$result = $conn->query($SQL); 

    if ($result->num_rows>0)
    {
        //user information available in database
        echo "Login successful";
        echo "<br><br> re-directing to members page";
        $_SESSION['userlogin'] = $User_login;
        header ( 'refresh:5; url=member.php?id='.$Username ); //re-directing to member page
    }

And ive added the if isset:

<?php //Start of the PHP script
session_start();


if(!isset($_SESSION['userlogin']))
{

}

The header(…) function is being used incorrectly and if you temporarily set the following functions at the top of the page, errors and warnings will be displayed. Copying and pasting the error and warning messages into your browser will produce solutions that may be tried.

<?php
ini_set( 'display_errors', 'true' );
error_reporting( -1 );

// your original script follows here

Edit:
If solved ok then please supply the correct script, otherwise the reported errors and warnings.

1 Like

Did you fix the fundamental flaws in the login script mentioned already?

The lack of response and the code errors I pointed out remaining, makes me assume they were ignored.

The error reporting should help highlight the problems too.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.