Reputation: 31
Hi i'm a noob when it comes to PHP but im making a page where after you login you go to the homepage, but when im at the homepage logged in and refreshes the page i get logged out.
Here the code for my login. `
session_start();
require('connect.php');
if (isset($_POST['username']) and isset($_POST['password'])){
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM `user` WHERE username='$username' and password='$password'";
$result = mysqli_query($connection, $query) or die(mysqli_error($connection));
$count = mysqli_num_rows($result);
if ($count == 1){
$_SESSION['username'] = $username;
header("Location: index.php");
}else{
echo "Invalid Login Credentials.";
and the code for my index.php
<?php
require'connect.php';
session_start();
if (!isset($_SESSION['username'])){
echo" not logged in";
}else {
echo "logged in";
}
?>
Upvotes: 1
Views: 1811
Reputation: 757
Looks like a small issues as not much of php code is involved here. Try running this code without
require('connect.php');
If it still doesn't get resolved, I would recommend you to check with the code in connect.php file.
Upvotes: 0
Reputation: 6252
your login page has:
session_start();
require('connect.php');
whereas your home page has:
require'connect.php';
session_start();
Try to be consistent. From the manual:
"To use cookie-based sessions, session_start() must be called before outputting anything to the browser."
Make sure you're calling session_start()
first, in both pages. Make sure you don't have any white space or anything else being outputted first. For example:
<?php
session_start();
// white space above PHP tag
<?php
session_start();
That should solve your problem.
Upvotes: 2