I'm relatively new to PHP and have recently created a small website for friends and family to upload and share photos, protected by a very simple login system.
While I'm aware what I'm doing isn't best practice and you'd never use this in a "published" site, I'd like to use this as learning experience to improve my coding, and would appreciate any pointers as to best practice and efficiency/security improvements.
The website contains no sensitive information and the login was purely to prevent unwanted uploading of files. The username isn't checked against anything and is only used to log who's uploaded a file. The password is shared for all users.
This script, login.php, is included at the top of each page and checks if the user is logged in - if not then redirect to homepage where the login form is displayed. If already logged in, then display some internal links instead of form.
if(!isset($_SESSION)){ session_start(); }
/***********************************************************/
//check if home page
if (/*code to check if outside root directory*/) }{$notHomePage = true;}
if($notHomePage and ($_SESSION['allow'] == false or !isset($_SESSION['allow'])) ) {
$_SESSION['error'] = 'Please enter your name and password!';
header('Location: index.php');
exit();
}
/***********************************************************/
function readCookie() {
if (isset($_COOKIE["username"])) {
$name = $_COOKIE["username"];
}
return $name;
}
/***********************************************************/
function loginForm() {
if($_SESSION['allow']) {
//display internal links and logout link
echo "<p><a href=\"login.php?logout\">Logout</a></p>";
}
else {
if(isset($_SESSION['error'])) {
echo "<div>" . $_SESSION['error'] . "</div>";
unset($_SESSION['error']);
}
$name = readCookie();
echo "<form method=\"post\" action=\"login.php\">
<input type=\"text\" value=\"$name\" name=\"name\"><label>Name</label>
<input type=\"password\" name=\"password\"><label>Password</label>
<button type=\"submit\" name=\"submit\">Login</button>
</form>";
}
}
/***********************************************************/
function login() {
$days = 30;
if(trim($_POST['name']) == "" || trim($_POST['password']) == "") {
$_SESSION['error'] = 'Please enter your name and password!';
header('Location: index.php');
exit();
}
$name = $_POST['name'];
$password = $_POST['password'];
$pass = "password"; //passsword goes here
if ($password != $pass) {
$_SESSION['error'] = 'Please enter the correct password!';
header('Location: index.php');
exit();
}
else {
$_SESSION['allow'] = true;
header('Location: index.php');
}
if($days) $expire = time()+60*60*24*$days;
setcookie("username", $name, $expire,"/");
}
/***********************************************************/
if($_SERVER['REQUEST_METHOD'] == "POST") {
login();
}
if($_SERVER['QUERY_STRING'] == "logout") {
$_SESSION['allow'] = false;
header("Location: index.php");
exit;
}
?>