I just wrote some PHP to let a client lock off a their one-page site from the public using a password. No users and no database. Just checking the password the user enters and testing it against the chosen phrase. This should be simple (right?) but I havn't built this sort of thing before. Let me know what you think, and whether it could be done better. Thanks!
includes/session.php
class Session {
private $logged_in;
function __construct() {
session_start();
$this->check_login();
}
// Return whether they are logged in.
public function is_logged_in() {
return $this->logged_in;
}
// When initialized, check to see if the user is logged in.
private function check_login() {
if (isset($_SESSION['logged_in'])) {
// If logged in, take this action
$this->logged_in = true;
} else {
// If not logged in, take this action
$this->logged_in = false;
}
}
// Set the session. User will remain logged in.
public function login() {
$_SESSION['logged_in'] = 1;
$this->logged_in = true;
}
// Log out. Unset session and destroy it.
public function logout() {
unset($_SESSION['logged_in']);
$this->logged_in = false;
session_destroy();
}
public function check_pass($pass) {
$pass = @strip_tags($pass);
$pass = @stripslashes($pass);
if ($pass !== 'TheChosenPassword') return false;
return true;
}
}
login.php:
require_once('includes/session.php');
// If already logged in just send them to index.php
if ($session->is_logged_in()) {
header('Location: index.php');
exit;
}
// Create the var in the global scope.
$msg = 'This page is private.<br> Please enter the password.';
// If the form was submitted ...
if (isset($_POST['submit'])) {
// Make sure they entered a pass
if (!$_POST['pass']) {
$msg = "Please enter a password.";
} else {
// If they entered a pass, grab it and trim it.
$pass = trim($_POST['pass']);
// Now check the pass
if ($session->check_pass($pass)) {
$session->login();
header('Location: index.php');
exit;
} else {
$msg = "Sorry, that password is incorrect.";
} // Endif checkpass
} // endif isset(pass)
} // Endif isset(post)
?> <!-- The form is bellow -->
index.php
require_once('includes/session.php');
if (!$session->is_logged_in()) {
header('Location: login.php');
exit;
}
You can probably guess from the code that the form just has an <input>
with a name of 'pass' and a submit button with a name of 'submit'. Also a <small>
tag in which i echo $msg
. So, any thoughts on how this could be improved? Did I make any glaring mistakes? Thanks for the help!
?>insert evil code
". \$\endgroup\$