SITUATION
I have made the following login form:
<?php
session_start();
session_regenerate_id(TRUE);
$username = $_POST['username'];
$password = $_POST['password'];
$url_to_open_after_success_login = $_POST['sezione'];
//Connect to my database
try {
$pdo = new PDO('mysql:host=0.0.0.0;dbname=name', 'user', 'passw');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo "non riesco a connettere. perchè -> " . $e->getMessage();
exit();
}
//The table "accessi" has 2 fields that are "username" and "password"
//From this table I grab the data
try {
$query_mag = $pdo->prepare("SELECT * FROM accessi WHERE username = ?");
$query_mag->bindParam(1 , $username, PDO::PARAM_INT);
$query_mag->execute();
} catch (PDOException $e) {
echo "Unable to execute the query. ". $e->getMessage();
exit();
}
$dati_utente = $query_mag->fetch();
//CHECK IF THE PASSWORD IS CORRECT OR NOT
if ( password_verify($password, $dati_utente[1]) ) {
//login executed
$_SESSION["login"] = 1;
if ($url_to_open_after_success_login == 'something') {
header('location: /blabla/aaa.php');
} else {
header('location: /blabla2/bbb.php');
}
} else {
//WRONG PASSWORD! You are not allowed to access so go back to the home
header('location: /');
}
?>
The code above is pretty easy. I connect to the database, then I make a query to get the password (hashed of course) of a particular user. Then if the password is correct I am redirected to a page.
Only if the login successfully happened, I am using $_SESSION["login"] = 1;.
PROBLEM
On the top of each page I have the following code:
<?php
session_start();
if (!isset($_SESSION["login"])) { header('location: /error_page.php'); }
?>
<html>
<head>
//html/css/js code here...
If you look at the PHP code, you can understand that (if the user did not log in successfully) the page immediatly redirects to the error page. My question is the following.
Q: is this a safe way to check if the user logged in? should I avoid this redirect-way and try something else?
When a logged member wants to log out, I have made a logout.php file that looks like this:
<?php
session_start();
session_regenerate_id(TRUE);
$_SESSION = array();
//delete the session cookie
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
session_destroy();
header('location: /');
?>