I have just started messing around with PHP/SQL and came up with a simple sign-in application that checks if your sign-in information is valid based on database information. Here is my code:
<!DOCTYPE HTML>
<html>
<head>
<title>Sample Database Page</title>
<style>
body {
font-family: sans-serif;
}
.error {
display: none;
margin: 10px;
align-content: center;
justify-content: flex-start;
background-color: red;
border-radius: 5px;
}
.error > p {
display: block;
width: auto;
}
</style>
</head>
<body>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" id="signInForm">
Username:
<input type="text" name="username" maxlength="15"/>
Password:
<input type="text" name="password" maxlength="15"/>
<input type="submit"/>
</form>
<div class="errorContainer">
<div class="error" id="usernameError1">
<img src="exclamation_mark.png" width="35px"/>
<p>Your username contains invalid characters</p>
</div>
<div class="error" id="passwordError1">
<img src="exclamation_mark.png" width="35px"/>
<p>Your password contains invalid characters</p>
</div>
<div class="error" id="usernameError2">
<img src="exclamation_mark.png" width="35px"/>
<p>The username you enter could not be found. Please try again.</p>
</div>
<div class="error" id="passwordError2">
<img src="exclamation_mark.png" width="35px"/>
<p>The password is incorrect. Please try again.</p>
</div>
</div>
<?php
require __DIR__ . "/helper_functions.php";
# Contains 7 functions
# openConnection: opens the database connection
# closeConnection: closes the database connection
# isValidUsername: checks user input against this regex: /^[A-Za-z0-9_]+$/
# isValidPassword: checks user input against this regex: /^[A-Za-z0-9!@$#%_]+$/
# escapeSymbols: escapes $ (\$)
# displayError: uses Javascript to set the display of the selected error message to flex
# displayUsername: inserts the provided username back into it's input field using Javascript if an error has occurred
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$conn = openConnection();
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$return = false;
if (!isValidUsername($_POST["username"])) {
displayError("usernameError1");
$return = true;
}
if (!isValidPassword($_POST["password"])) {
displayError("passwordError1");
$return = true;
}
if ($return) {
displayUsername($_POST["username"]);
closeConnection($conn);
return;
}
$username = $_POST["username"];
$password = escapeSymbols($_POST["password"]);
$sql = "SELECT * FROM `customer_data` WHERE username = '" . $username . "'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) == 0) {
displayError("usernameError2");
closeConnection($conn);
return;
}
$row = $result->fetch_assoc();
$correctPassword = $row["password"];
if ($password == $correctPassword) {
echo "Access granted!";
closeConnection($conn);
} else {
displayError("passwordError2");
displayUsername($_POST["username"]);
closeConnection($conn);
}
}
?>
</body>
</html>
When you submit the form, a few things happen:
- A connection to the database is set up. If the database cannot be found, the application dies.
- The application checks if the submitted fields don't contain invalid characters. If one does, an error is displayed for that field, and if both do, error messages are displayed for each. The submitted username is displayed again in it's input field. This process stops.
- The username is then checked for in the database. If it is not found, an error message is displayed, the username submitted by the user is displayed in it's input field, and this process is stopped. Otherwise, it checks if the password (with $ escaped) is the users. If it is, the program displays "Access granted!" and the input is valid. Otherwise, an error message is displayed, the previously submitted username is displayed in it's input field, and this process ends.
What can I do to improve this program?
UPDATE:
Here is the code for helper_functions.php as requested:
<?php
function openConnection() {
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$db = "online_store_database";
$conn = new mysqli($dbhost, $dbuser, $dbpass, $db) or die("Connect failed: %s\n" . $conn -> error);
return $conn;
}
function closeConnection($conn) {
$conn -> close();
}
function isValidUsername($data) {
return preg_match('/^[A-Za-z0-9_]+$/', $data);
}
function isValidPassword($data) {
return preg_match('/^[A-Za-z0-9!@$#%_]+$/', $data);
}
function escapeSymbols($string) {
return str_replace("$", "\$", $string);
}
function displayError($errorName) {
echo "<script type='text/javascript'>document.getElementById('" . $errorName . "').style.display = 'flex';</script>";
}
function displayUsername($username) {
echo "<script async type='text/javascript'>document.getElementsByName('username')[0].value = '" . $username . "';</script>";
}
?>
mysqli_num_rows
and then->fetch_assoc
) \$\endgroup\$