session_auth/cadb.php
<?php
// Users
// make the password with: echo -n 'mypassword' |md5sum
$login_error='<h2>Login error</h2><script>window.location = "index.php"; </script>';
$htmlFormLogin='';
$dsn='pgsql:host=localhost;port=5432;dbname=mydb;user=myuser;password=mypassword';
$table='users';
$userField="username";
$passField="password";
$activeField="active";
$sql="select * from $table where $userField = :USER and $passField = :PASS and $activeField = '1' ;";
function checkAuth($user, $pass)
{
global $dsn, $table, $userField, $passField, $activeField, $sql;
$c=0;
try {
$dbh = new PDO($dsn);
$stmt = $dbh->prepare($sql);
$stmt->bindParam(":USER", $user);
$stmt->bindParam(":PASS", $pass);
if (! $stmt->execute() ) echo '<p>Error in query .</p>';
while ($row = $stmt->fetch(PDO::FETCH_BOUND)) $c++;
if ($c!=0)
{
return true;
}else{
return false;
}
$dbh = null;
} catch (PDOException $e) {
print "Error : " . $e->getMessage() . "<br/>";
die();
}
}
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();
}
?>