<?php session_start(); // start session
// set timezone
date_default_timezone_set("America/Detroit");
// check for authorization
$auth = isset($_SESSION['auth']) ? $_SESSION['auth'] : false;
$self = htmlspecialchars(basename($_SERVER['SCRIPT_NAME']));
$error = '';
$con = '';
$total = '';
$create = false;
// in from form
$submit = isset($_POST['submit']) ? $_POST['submit'] : null;
$email = isset($_POST['email']) ? $_POST['email'] : null;
$password = isset($_POST['password']) ? $_POST['password'] : null;
include("../includes/open-db.php");
if ($submit == 'Logon')
{
// check db for user email address (unique id)
$id = 0;
$query = "SELECT id FROM users WHERE email = '$email' ";
$result = mysqli_query($con, $query) or die(report(mysqli_error($con), $query, __LINE__, __FILE__));
$row = mysqli_fetch_array($result);
$id = $row['id'];
if ($id > 0) // The user's email was found.
{
$query = "SELECT password FROM users WHERE id = '$id' ";
$result = mysqli_query($con, $query) or die(report(mysqli_error($con), $query, __LINE__, __FILE__));
$row = mysqli_fetch_array($result);
$pw = $row['password'];
// do passwords match?
if ($password == $pw)
{
// set auth session to true
$_SESSION['auth'] = true;
// send user to protected page
header('Location:protected-page.php');
exit();
}
else
{
$error = 'Error in password -- Please try again.';
$_SESSION['auth'] = false;
}
}
else
{
$error = 'Email not in database. Do you want to create an account?';
$_SESSION['auth'] = false;
$create = true;
}
}
if ($submit == 'Create')
{
$regis_date = date("Y-m-d : G:i:s"); // example 2022-10-22 : 15:30:34
$query = "INSERT INTO users (email, password, regis_date) VALUES ('$email', '$password', '$regis_date') ";
$result = mysqli_query($con, $query) or die(report(mysqli_error($con), $query, __LINE__, __FILE__));
// new account -- require a real logon
// set auth session to false
$_SESSION['auth'] = false;
// send user to logon page to logon with new account
header("Location:$self");
exit();
}
include('../includes/close-db.php');
include('../includes/header4.php');
if ($error)
{
echo("<p>$error</p>");
}
?>
<h1>Login Demo</h1>
<form name="my_form" action="<?php echo($self); ?>" method="POST">
<p>
<label for="email">Email:</label>
<input type="text" name="email" id="email" size="20" placeholder="email address">
<br>
<label for="password">Password:</label>
<input type="password" size="20" id="password" name="password" placeholder="password">
<br><br>
<input type="submit" name="submit" id="submit" value="Logon">
<?php
if ($create == true)
{
?>
<input type="submit" name="submit" id="submit" value="Create">
<br><br>
<a href=forgot-password.php?>Forgot Password</a>
<?php
}
?>
</p>
</form>
<?php include("../includes/footer4.php"); ?>
<?php //-----------=========== functions ===========--------------
function report($sql_error, $query, $line, $file)
{
echo($sql_error . '<br>' . $query . '<br>' . $line . '<br>' . $file . '<br>');
}
?>
Last modified: December 01 2022
Line Count: 125