login.html
<form action="login.php" method="post">
<input type="text" name="login" id="login"/>
<input type="password" name="password"/>
<input type="text" name="form_login" hidden readonly/>
<input type="submit">
</form>
login.php
<?php
include 'validation.php';
include 'database.php';
include 'functions.php';
if (formSubmit('form_login')) {
if (formValid(['login', 'password'], [VALIDATE_LOGIN, VALIDATE_PASSWORD])) {
if(isUserExist('login', 'password')) {
echo "hi";
}
}
}
functions.php
<?php
function formSubmit(string $formName)
{
if (array_key_exists($formName, $_POST)) {
return true;
}
return false;
}
function formValid(array $fields, array $filters)
{
for ($i = 0; $i < count($filters); $i++) {
if(!preg_match($filters[$i], filter_input_array(INPUT_POST)[$fields[$i]])) {
return false;
};
}
return true;
}
function isUserExist($loginPostField, $passwordPostFiled, $allowDisabled = true) {
$login = filter_input_array(INPUT_POST)[$loginPostField];
$password = filter_input_array(INPUT_POST)[$passwordPostFiled];
if(userExistInDatabase($login, $password)) {
return true;
}
return false;
}
function userExistInDatabase($login, $password)
{
$mysqli = new \mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if ($mysqli->connect_errno) {
echo 'error:' . __METHOD__ . " : " . __LINE__; die;
}
$sql = "SELECT id FROM users WHERE login = $login AND password = " . password_hash($password, PASSWORD_BCRYPT);
if (!$result = $mysqli->query($sql)) {
echo 'error:' . __METHOD__ . " : " . __LINE__; die;
}
if ($result->num_rows === 1) {
return true;
}
return false;
}
database.php
<?php
define('DB_HOST', '...');
// ...
validation.php
<?php
define('VALIDATE_LOGIN', '/^(\w{3,12})$/');
// ...