Just wanted to run through my PHP session handling and get some feedback and tips with regard to what is good (if anything!), what could be better and what is either plain wrong, or using out of date methods.
Just as a bit of background, I have only ever dabbled with PHP (and many years ago that was) and want to try and embrace the OOP side of it.
Every page that is required to be part of a session has the following at the top:
<?php
include_once 'Session.php';
$session = new Session();
$session->authenticate();
?>
Session.php is as follows:
class Session {
const password = "5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8";
private $sessionInfo;
public function __construct() {
session_start();
if (!isset($_SESSION['sessionInfo'])) {
$sessionInfo = new SessionInfo();
$_SESSION['sessionInfo'] = $sessionInfo;
} else {
$sessionInfo = $_SESSION['sessionInfo'];
}
}
public function authenticate() {
if (isset($_SESSION['loggedin'])) {
if ($_SESSION['loggedin'] === true) {
return;
}
}
header('Location: login.php');
}
public function logIn($password) {
if (sha1($password) === self::password) {
$_SESSION['loggedin'] = true;
header('Location: index.php');
}
}
public function logOut() {
unset($_SESSION['loggedin']);
session_destroy();
header('Location: login.php');
}
public function getSessionInfo() {
return $this->sessionInfo;
}
}
?>
SessionInfo is currently just a blank class, it's intended purpose is to act as an information store for the current session.
login.php:
<?php
include_once 'Session.php';
if(isset($_POST['submit'])) {
if(isset($_POST['password'])) {
$session = new Session();
$session->logIn($_POST['password']);
}
}
?>
<html>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<input type="password" name="password" />
<input type="submit" name="submit" />
</form>
</body>
</html>
Do I need to call die()
(or exit()
seeing as they are identical) after a failed authenticate to terminate any page which may attempt to load? Or do I need to return a boolean and then terminate from the calling page?
Please disregard the use of SHA1 and the hashed password in the file, I will be extending this to use a MySQL background, and hope to incorporate the use of a salted hash. I will be using prepared statements, will this be sufficient to protect from SQL injection and allow me to not bother filtering $_POST[...]
?
Also, I realise that the location headers may better be stored as a class constant in case I wish to change the locations.
5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8
the hash of any important password? If it is, CHANGE IT NOW! \$\endgroup\$