session_auth/ca.php
<?php
// Users
// make the password with: echo -n 'mypassword' |md5sum
$accounts['fabio'] = 'a53bd0415947807bcb95ceec535820ee';
$accounts['rita'] = '2794d223f90059c9f705c73a99384085';
$login_error='<h2>Login error</h2><script>window.location = "index.php"; </script>';
$htmlFormLogin='';
function checkAuth($user, $pass)
{
global $accounts;
if (array_key_exists($user, $accounts) && $accounts[$user]==$pass)
{
return true;
}else{
return false;
}
}
function checkUsername($username)
{
if (ctype_alnum($username)) {
return true;
}else{
return false;
}
}
function checkPassword($password)
{
if (ctype_alnum($password)) {
return true;
}else{
return false;
}
}
// Not edit
session_start();
if (isset($_POST["login_btn"]))
{
if (!checkUsername($_POST["username"]) || !checkPassword($_POST["password"]))
{
echo "<p>Error...</p>";
die();
}
$username=filter_var($_POST["username"], FILTER_SANITIZE_STRING);
$password=filter_var(md5($_POST["password"]), FILTER_SANITIZE_STRING);
if (checkAuth($username,$password))
{
//logged in
$_SESSION["username"]=$username;
$_SESSION["password"]=$password;
return;
}else{
//login error
echo $login_error;
die();
}
}else{
if (isset($_SESSION["username"]))
{
if (checkAuth($_SESSION["username"],$_SESSION["password"])) return ;
}
if (!empty($htmlFormLogin))
{
echo $htmlFormLogin;
}else{
echo '
<!DOCTYPE html >
<html >
<head>
<title>Login</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
</head>
<body>
<h2>Login</h2>
<form action="'.$_SERVER['REQUEST_URI'].'" method="post">
<div><label> Username: <input id="username" name="username" type="text" placeholder="Insert username"></label></div>
<div><label> Password: <input id="password" name="password" type="text" placeholder="Insert password"></label></div>
<div><button id="login_btn" name="login_btn" >Login</button></div>
</form>
</body>';
}
die();
}
?>