У меня сейчас проблемы с хешированием. Вот немного фона;
Пользователь создает учетную запись, и его пароль хэшируется с использованием password_hash ($ password, PASSWORD_BCRYPT). Затем, когда они входят в систему, пароль проверяется через password_verify, и если он верный, они будут зарегистрированы.
Однако, когда пользователь заходит в свой профиль и редактирует свои данные, изменяя свой пароль, он никогда не сможет войти снова. Кроме того, если сотрудник меняет пароль пользователя, он все равно не может войти в систему.
Я пытался осмотреться и решить эту проблему, но ничего не могу найти, и что самое странное, что когда сотрудник (скажем, учетная запись администратора) меняет пароль другого сотрудника, он может нормально войти в систему со своим новым паролем. ? Я сделал почти тот же код, что и рабочий, меняя пароль и перефразируя код, но он все равно не работает.
Подписаться:
<?php
$servername = "localhost"; /*The host of the MySQL name.*/
$username = "root"; /*MySQL username.*/
$password = ""; /*MySQL password.*/
$dbname = ""; /*MySQL database name.*/
$tablename = "clientinformation"; /*The table name that will be used from the database.*/
/*This line check if the website can connect to the database, else it will return an error message.*/
mysql_connect("$servername", "$username", "$password")or die("Cannot connect to the database.");
/*This line checks if the website can select the database the website is requesting, else it will return an error message.*/
mysql_select_db("$dbname")or die("Cannot select the database.");
$clienttitle = $_POST["clienttitle"]; /*Retrieves the ClientTitle input from the user.*/
$clientforename = $_POST["clientforename"]; /*Retrieves the ClientForename input from the user.*/
$clientsurname = $_POST["clientsurname"]; /*Retrieves the ClientSurname input from the user.*/
$phonenumber = $_POST["phonenumber"]; /*Retrieves the PhoneNumber input from the user.*/
$clientusername = $_POST["clientusername"]; /*Retrieves the Username input from the user.*/
$clientpassword = $_POST["clientpassword"]; /*Retrieves the ClientPassword input from the user.*/
$emailaddress = $_POST["emailaddress"]; /*Retrieves the EmailAddress input from the user.*/
$billingaddress = $_POST["billingaddress"]; /*Retrieves the BillingAddress input from the user.*/
/*Here, each of the inputs are put through the 'stripslashes' function, which stops a MySQL injection attack.*/
$clienttitle = stripslashes($clienttitle);
$clientforename = stripslashes($clientforename);
$clientsurname = stripslashes($clientsurname);
$phonenumber = stripslashes($phonenumber);
$clientusername = stripslashes($clientusername);
$clientpassword = stripslashes($clientpassword);
$emailaddress = stripslashes($emailaddress);
$billingaddress = stripslashes($billingaddress);
/*The use of mysql_real_escape_string also stops a MySQL injection attack.*/
$clienttitle = mysql_real_escape_string($clienttitle);
$clientforename = mysql_real_escape_string($clientforename);
$clientsurname = mysql_real_escape_string($clientsurname);
$phonenumber = mysql_real_escape_string($phonenumber);
$clientusername = mysql_real_escape_string($clientusername);
$clientpassword = mysql_real_escape_string($clientpassword);
$emailaddress = mysql_real_escape_string($emailaddress);
$billingaddress = mysql_real_escape_string($billingaddress);
$hashedclientpassword = password_hash($clientpassword, PASSWORD_BCRYPT);
$query = "INSERT INTO $tablename (ClientID, ClientTitle, ClientForename, ClientSurname, PhoneNumber, Username, EmailAddress, ClientPassword, BillingAddress, SignUpDate)VALUES(NULL, '$clienttitle', '$clientforename', '$clientsurname', '$phonenumber', '$clientusername', '$emailaddress', '$hashedclientpassword', '$billingaddress', CURRENT_TIMESTAMP)";
$result = mysql_query($query);
if($result){
echo "Successful";
header("location:Index.php");
} else {
echo ("Unsuccessful : " . mysql_error());
}
mysql_close();
?>
Проверьте логин:
<?php
$servername = "localhost"; /*The host of the MySQL name.*/
$username = "root"; /*MySQL username.*/
$password = ""; /*MySQL password.*/
$dbname = ""; /*MySQL database name.*/
$tablename = "clientinformation"; /*The table name that will be used from the database.*/
/*This line check if the website can connect to the database, else it will return an error message.*/
mysql_connect("$servername", "$username", "$password")or die("Cannot connect to the database.");
/*This line checks if the website can select the database the website is requesting, else it will return an error message.*/
mysql_select_db("$dbname")or die("Cannot select the database.");
/*This retrieves the data inserted by the user from the previous page. In this case, it is retrieving the username and password the user entered.*/
$userusername = $_POST["Username"];
$userpassword = $_POST["ClientPassword"];
/*Here, these four lines of code are used to stop an MySQL injection attack on the website/database.*/
$userusername = stripslashes($userusername);
$userpassword = stripslashes($userpassword);
$userusername = mysql_real_escape_string($userusername);
$userpassword = mysql_real_escape_string($userpassword);
$sql = "SELECT ClientPassword FROM $tablename WHERE Username = '$userusername'";
$result = mysql_query($sql);
$datarow = mysql_fetch_array($result);
$hasheduserpassword = $datarow['0'];
if (password_verify($userpassword, $hasheduserpassword)) {
session_start();
$_SESSION['Username'] = $userusername;
$_SESSION['ClientPassword'] = $hasheduserpassword;
header("Location:IndexUserLogin.php");
} else {
header("location:WrongPU.php");
}
?>
Пользователь редактирует свои данные:
<?php
session_start();
if(! $_SESSION['Username']) {
header("location:Index.php");
}
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "";
$tablename = "clientinformation";
mysql_connect("$servername", "$username", "$password") or die("Cannot connect to the database.");
mysql_select_db("$dbname") or die ("Cannot select the database.");
$clientid = $_POST["clientid"];
$clienttitle = $_POST["clienttitle"];
$clientforename = $_POST["clientforename"];
$clientsurname = $_POST["clientsurname"];
$phonenumber = $_POST["phonenumber"];
$clientusername = $_POST["clientusername"];
$emailaddress = $_POST["emailaddress"];
$clientpassword = $_POST["clientpassword"];
$billingaddress = $_POST["billingaddress"];
$clientid = stripslashes($clientid);
$clienttitle = stripslashes($clienttitle);
$clientforename = stripslashes($clientforename);
$clientsurname = stripslashes($clientsurname);
$phonenumber = stripslashes($phonenumber);
$clientusername = stripslashes($clientusername);
$emailaddress = stripslashes($emailaddress);
$clientpassword = stripslashes($clientpassword);
$billingaddress = stripslashes($billingaddress);
$clientid = mysql_real_escape_string($clientid);
$clienttitle = mysql_real_escape_string($clienttitle);
$clientforename = mysql_real_escape_string($clientforename);
$clientsurname = mysql_real_escape_string($clientsurname);
$phonenumber = mysql_real_escape_string($phonenumber);
$clientusername = mysql_real_escape_string($clientusername);
$emailaddress = mysql_real_escape_string($emailaddress);
$clientpassword = mysql_real_escape_string($clientpassword);
$billingaddress = mysql_real_escape_string($billingaddress);
$hashedclientpassword = password_hash($clientpassword, PASSWORD_BCRYPT);
$query = "UPDATE $tablename SET ClientTitle = '$clienttitle', ClientForename = '$clientforename', ClientSurname = '$clientsurname', PhoneNumber = '$phonenumber', Username = '$clientusername', EmailAddress = '$emailaddress', ClientPassword = '$hashedclientpassword', BillingAddress = '$billingaddress' WHERE ClientID = '$clientid'";
$result = mysql_query($query);
if($result) {
echo "Successful update";
header("Location:UserCP.php");
} else {
echo ("ERROR : " . mysql_errno . " " . mysql_error());
}
?>
Редактировать данные о сотрудниках (работы)
<?php
session_start();
if($_SESSION['EmployeeUsername'] !== "Admin") {
header("location:Index.php");
}
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "";
$tablename = "employeelogin";
mysql_connect("$servername", "$username", "$password") or die("Cannot connect to the database.");
mysql_select_db("$dbname") or die ("Cannot select the database.");
$employeeid = $_POST['employeeid'];
$employeeusername = $_POST['employeeusername'];
$employeepassword = $_POST['employeepassword'];
$employeename = $_POST['employeename'];
$employeesurname = $_POST['employeesurname'];
$employeeid = stripslashes($employeeid);
$employeeusername = stripslashes($employeeusername);
$employeepassword = stripslashes($employeepassword);
$employeename = stripslashes($employeename);
$employeesurname = stripslashes($employeesurname);
$employeeid = mysql_real_escape_string($employeeid);
$employeeusername = mysql_real_escape_string($employeeusername);
$employeepassword = mysql_real_escape_string($employeepassword);
$employeename = mysql_real_escape_string($employeename);
$employeesurname = mysql_real_escape_string($employeesurname);
$hashedemployeepassword = password_hash($employeepassword, PASSWORD_BCRYPT);
$query = "UPDATE $tablename SET EmployeeID = '$employeeid', EmployeeUsername = '$employeeusername', EmployeePassword = '$hashedemployeepassword', EmployeeName = '$employeename', EmployeeSurname = '$employeesurname' WHERE EmployeeID = '$employeeid'";
$result = mysql_query($query);
if($result) {
echo "Successful update";
header("Location:EmployeeCP.php");
} else {
echo ("ERROR : " . mysql_errno . " " . mysql_error());
}
?>
Проверьте логин сотрудников (работа)
<?php
$servername = "localhost"; /*The host of the MySQL name.*/
$username = "root"; /*MySQL username.*/
$password = ""; /*MySQL password.*/
$dbname = ""; /*MySQL database name.*/
$tablename = "employeelogin"; /*The table name that will be used from the database.*/
/*This line check if the website can connect to the database, else it will return an error message.*/
mysql_connect("$servername", "$username", "$password")or die("Cannot connect to the database.");
/*This line checks if the website can select the database the website is requesting, else it will return an error message.*/
mysql_select_db("$dbname")or die("Cannot select the database.");
/*This retrieves the data inserted by the user from the previous page. In this case, it is retrieving the username and password the employee entered.*/
$employeeusername = $_POST["EmployeeUsername"];
$employeepassword = $_POST["EmployeePassword"];
/*Here, these four lines of code are used to stop an MySQL injection attack on the website/database.*/
$employeeusername = stripslashes($employeeusername);
$employeepassword = stripslashes($employeepassword);
$employeeusername = mysql_real_escape_string($employeeusername);
$employeepassword = mysql_real_escape_string($employeepassword);
$sql = "SELECT EmployeePassword FROM $tablename WHERE EmployeeUsername = '$employeeusername'";
$result = mysql_query($sql);
$datarow = mysql_fetch_array($result);
$hashedemployeepassword = $datarow['0'];
if (password_verify($employeepassword, $hashedemployeepassword)) {
session_start();
$_SESSION['EmployeeUsername'] = $employeeusername;
$_SESSION['EmployeePassword'] = $hashedemployeepassword;
header("Location:IndexEmployeeLogin.php");
} else {
header("location:WrongPU.php");
}
?>
Приветствия для всех и любых ответов
stripslashes()
а также mysql_real_escape_string()
для ввода пароля, функции password_hash () а также password_verify () принимать даже двоичный ввод и не подвержены SQL-инъекциям. Я предполагаю, что это уже решает вашу проблему.Экранирование должно выполняться как можно позже и только для данной целевой системы, поэтому функцию mysqli_real_escape_string () следует вызывать только для построения SQL-запроса.
clientinformation
а также employeelogin
), поле хэша пароля объявлено с 60 символами или больше.if(!isset($_SESSION['Username']))
"UPDATE $tablename SET EmployeeID = '$employeeid', ... WHERE EmployeeID = '$employeeid'";
И это хорошая привычка всегда вызывать exit после перенаправления:
header('Location: Index.php', true, 303);
exit;
Других решений пока нет …