I have a hand built website, and am triying to build a cms/admin-panel, and my username and password, are not stored in a database, but, in a two setup file like seen below.
index.php
<?php
session_start();
define('DS', TRUE); // used to protect includes
define('USERNAME', $_SESSION['username']);
define('SELF', $_SERVER['PHP_SELF'] );
if (!USERNAME or isset($_GET['logout']))
include('login.php');
// everything below will show after correct login
?>
login.php
<?php defined('DS') OR die('No direct access allowed.');
$users = array(
"user" => "userpass"
);
if(isset($_GET['logout'])) {
$_SESSION['username'] = '';
header('Location: ' . $_SERVER['PHP_SELF']);
}
if(isset($_POST['username'])) {
if($users[$_POST['username']] !== NULL && $users[$_POST['username']] == $_POST['password']) {
$_SESSION['username'] = $_POST['username'];
header('Location: ' . $_SERVER['PHP_SELF']);
}else {
//invalid login
echo "<p>error logging in</p>";
}
}
echo '<form method="post" action="'.SELF.'">
<h2>Login</h2>
<p><label for="username">Username</label> <input type="text" id="username" name="username" value="" /></p>
<p><label for="password">Password</label> <input type="password" id="password" name="password" value="" /></p>
<p><input type="submit" name="submit" value="Login" class="button"/></p>
</form>';
exit;
?>
Code Source: php - Easy login script without database - Stack Overflow
What is the best way to secure those file.
MD5()
. The logout function should also delete the session and expire the session cookie. There should be anexit()
after theheader()
calls or the rest of the page will be executed before the response is sent and the redirect response will include the login form which is wasteful.