I need some help with sessions on PHP, I'm making a user account system I was told that they're made using PHP sessions, I searched for some tips and made some tests, I ended up with this code:
<?php
$servername = "localhost";
$username = "myuser";
$password = "mypassword";
$dbname = 'mydb';
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST["submitbutton"])){
$user = $_POST["user"];
$password = $_POST["password"];
$usuario = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM user WHERE user = '".$user."' AND password = '".$password."'"));
if(!empty($usuario["user"]) || !empty($usuario["password"])){
$cookie_name = "cookie";
setcookie($cookie_name, " ", time() - (86400 * 30), "/");
$id = session_create_id();
$cookie_value = $id;
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
session_id($id);
session_start();
$_SESSION["user"] = $user;
header("Location:home.php");
} else{
echo "Error, password incorrect";
}
}
?>
<html>
<head>
<title>HOME</title>
</head>
<body>
<h1>LOGIN</h1>
<form action="" method="post">
<p>Usuário:</p>
<input type="text" name="user" id="user">
<p>Senha:</p>
<input type="password" name="password" id="password">
<p><input type="submit" value="Enter" name="submitbutton"><br></p>
</form>
</body>
So basically it is a form that checks if it was filled and proceeds to verify if the user params (user and password) match one in a database, if the data matches, it erases the site's cookie, creates a session id, creates a cookie and stores the session id on it, stores the session id, stores user data in the session, starts the session and redirects to the home page.
them in the home.php page I have a code to check if the user is logged, it does by checking if the cookie stored id matches the session id:
<?php
if(isset($_COOKIE["cookie"])) {
$session = $_COOKIE["cookie"];
session_start();
if (session_id() === $session){
//does nothing
} else {
$cookie_name = "cookie";
$cookie_value = session_id();
setcookie($cookie_name, $cookie_value, time() - (86400 * 30), "/");
session_destroy();
header("Location:index.php");
}
} else{
header("Location:index.php");
}
?>
This code is supposed to run on every page of the system, if the ids do not match, it finishes the session, erases the cookie and redirects to the login page, if it does not have a site cookie, it redirects to the login page.
Is this the way to do it? Is this code alright?