Смену пароля нельзя просто сделать в личном
кабинете. Дело в том, что пользователь может
оставить свой компьютер без присмотра (например,
в офисе), будучи авторизованным на нашем
сайте. В этом случае, если разрешить просто
менять пароль, то злоумышленник-недоброжелатель
сможет сменить пароль на другой, что, конечно
же, очень плохо.
Необходимо сделать так, чтобы смена пароля
на новый требовала ввода старого пароля.
Давайте реализуем страницу changePassword.php
,
зайдя на которую пользователь увидит форму
с двумя инпутами — в первый он должен будет
ввести свой старый пароль, а во вторую — новый:
<form action="" method="POST">
<input name="old_password">
<input name="new_password">
<input type="submit" name="submit">
</form>
По нажатию на кнопку отправки мы должны сделать
следующее:
<?php
$id = $_SESSION['id']; // id юзера из сессии
$query = "SELECT * FROM users WHERE id='$id'";
$result = mysqli_query($link, $query);
$user = mysqli_fetch_assoc($result);
$hash = $user['password']; // соленый пароль из БД
$oldPassword = $_POST['old_password'];
$newPassword = $_POST['new_password'];
// Проверяем соответствие хеша из базы введенному старому паролю
if (password_verify($oldPassword, $hash)) {
$newPasswordHash = password_hash($newPassword, PASSWORD_DEFAULT);
$query = "UPDATE users SET password='$newPasswordHash' WHERE id='$id'";
mysqli_query($link, $query);
} else {
// старый пароль введен неверно, выведем сообщение
}
?>
Реализуйте описанную смену пароля.
Подтверждение пароля
Есть еще один нюанс: старый и новый пароли
следует вводить в инпуты с типом password
.
Получается, что пользователь не будет видеть,
что именно он ввел вместо нового пароля,
что чревато ошибками. Необходимо сделать
так, чтобы для нового пароля вводился сам
пароль и его подтверждение:
<form action="" method="POST">
<input type="password" name="old_password">
<input type="password" name="new_password">
<input type="password" name="new_password_confirm">
<input type="submit" name="submit">
</form>
Реализуйте подтвержедние пароля при его смене.
(PHP 5, PHP 7, PHP 8, PECL OCI8 >= 1.1.0)
oci_password_change — Изменяет пароль пользователя Oracle
Описание
oci_password_change(
resource $connection
,
string $username
,
string $old_password
,
string $new_password
): bool
oci_password_change(
string $database_name
,
string $username
,
string $old_password
,
string $new_password
): resource
Функция oci_password_change() особенно полезна для скриптов PHP
командной строки или при использовании непостоянных соединений во всем приложении PHP.
Список параметров
-
connection
-
Идентификатор соединения, возвращаемый функцией
oci_connect() или oci_pconnect(). -
username
-
Имя пользователя Oracle.
-
old_password
-
Старый пароль.
-
new_password
-
Новый пароль.
-
database_name
-
Имя базы данных.
Возвращаемые значения
Если указан параметр connection
, oci_password_change() возвращает true
в случае успешного выполнения или false
в случае возникновения ошибки.
Если указан параметр connection
, oci_password_change() возвращает ресурс соединения в случае успешного выполнения или false
в случае возникновения ошибки.
Примеры
Пример #1 Пример использования oci_password_change() с изменением пароля уже подключённого пользователя
<?php
$dbase
= 'localhost/orcl';
$user = 'cj';
$current_pw = 'welcome';
$new_pw = 'geelong';$c = oci_pconnect($user, $current_pw, $dbase);
oci_password_change($c, $user, $current_pw, $new_pw);
echo "Новый пароль : " . $new_pw . "n";?>
Пример #2 Пример использования oci_password_change() с подключением и изменением пароля одновременно
<?php
$dbase
= 'localhost/orcl';
$user = 'cj';
$current_pw = 'welcome';
$new_pw = 'geelong';$c = oci_pconnect($user, $current_pw, $dbase);
if (!$c) {
$m = oci_error();
if ($m['code'] == 28001) { // "ORA-28001: the password has expired"
// Подключение и сброс пароля одновременно
$c = oci_password_change($dbase, $user, $current_pw, $new_pw);
if ($c) {
echo "Новый пароль : " . $new_pw . "n";
}
}
}
if (!
$c) { // Ошибка не совпадала с 28001, или не получилось изменить пароль
$m = oci_error();
trigger_error('Не удалось подключиться к базе данных: '. $m['message'], E_USER_ERROR);
}// Использование подключения $c
// ...?>
Примечания
Замечание:
Изменение пароля с помощью этой функции или непосредственно в Oracle
должно выполняться аккуратно, поскольку PHP-приложение может продолжать
использовать в постоянных соединениях данные аутентификации последнего удачного подключения,
которые уже устарели. Наилучшим решением может быть перезапуск всех веб-серверов после
смены пароля.
Замечание:
При обновлении библиотеки клиента Oracle или базы данных от версии установки до
версии 11.2.0.3 и выше функция oci_password_change() может
вернуть ошибку «ORA-1017: invalid username/password» (Неверные имя пользователя/пароль),
если версии и клиента и сервера обновлены в одно время.
Замечание:
Второй набор параметров функции oci_password_change() доступен
начиная с версии OCI8 1.1.
Замечание:
В версиях PHP ниже 5.0.0 эта функция называлась
ocipasswordchange().
В PHP 5.0.0 и выше ocipasswordchange() является
алиасом oci_password_change() для обратной совместимости,
вы можете продолжать использовать это имя, однако это не рекомендуется.
There are no user contributed notes for this page.
I am working on a section of code that changes a password in a database upon completion of the following form:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Password Change</title>
</head>
<body>
<h1>Change Password</h1>
<form method="POST" action="password_change.php">
<table>
<tr>
<td>Enter your UserName</td>
<td><input type="username" size="10" name="username"></td>
</tr>
<tr>
<td>Enter your existing password:</td>
<td><input type="password" size="10" name="password"></td>
</tr>
<tr>
<td>Enter your new password:</td>
<td><input type="password" size="10" name="newpassword"></td>
</tr>
<tr>
<td>Re-enter your new password:</td>
<td><input type="password" size="10" name="confirmnewpassword"></td>
</tr>
</table>
<p><input type="submit" value="Update Password">
</form>
<p><a href="home.php">Home</a>
<p><a href="logout.php">Logout</a>
</body>
</html>
And the the PHP:
<?php
session_start();
include 'dbconfig.php';
$username = $_POST['username'];
$password = $_POST['password'];
$newpassword = $_POST['newpassword'];
$confirmnewpassword = $_POST['confirmnewpassword'];
$result = mysql_query("SELECT password FROM user_info WHERE
user_id='$username'");
if(!$result)
{
echo "The username you entered does not exist";
}
else if($password!= mysql_result($result, 0))
{
echo "You entered an incorrect password";
}
if($newpassword=$confirmnewpassword)
$sql=mysql_query("UPDATE user_info SET password='$newpassword' where
user_id='$username'");
if($sql)
{
echo "Congratulations You have successfully changed your password";
}
else
{
echo "Passwords do not match";
}
?>
The problem I have at the moment is when I submit the submit button takes me to a read only page of this code.
Any suggestions?
Peter O.
31.7k14 gold badges78 silver badges93 bronze badges
asked Mar 19, 2013 at 20:43
4
On first looks I can figure out few major mistakes you made:
if you are comparing you should use
$newpassword == $confirmnewpassword
and not
$newpassword=$confirmnewpassword
secondly when you use if..elseif… loop format shold be
if (condition)
{
//code to be executed if condition is true;
}
else if (condition)
{
// code to be executed if condition is true;
}
else
{
//code to be executed if condition is false;
}
You apparently miss the else part in one of your such loops.
Please correct your syntax and try again…
answered Mar 19, 2013 at 21:05
Birju ShahBirju Shah
1,2209 silver badges18 bronze badges
u can 1st select a table and check a password is correct and if correct a update a password .else display a error message.hey this just update a password if old is password is match to update a password….,
Cracker World
$old_password=$_POST['old_password'];
$new_password=$_POST['new_password'];
$con_password=$_POST['con_password'];
$chg_pwd=mysql_query("select * from users where id='1'");
$chg_pwd1=mysql_fetch_array($chg_pwd);
$data_pwd=$chg_pwd1['password'];
if($data_pwd==$old_password){
if($new_password==$con_password){
$update_pwd=mysql_query("update users set password='$new_password' where id='1'");
$change_pwd_error="Update Sucessfully !!!";
}
else{
$change_pwd_error="Your new and Retype Password is not match !!!";
}
}
else
{
$change_pwd_error="Your old password is wrong !!!";
}}
answered Jan 29, 2014 at 10:45
1
You made a mistake here
This include 'dbconfig.php';
Should be like this include ('dbconfig.php');
answered Jun 29, 2018 at 7:37
After seen your script, i found that you have not use ‘==’ in your password comparison condition.
if($newpassword=$confirmnewpassword)
Which is wrong. You accepted the birju shah’s answer above which is pointing out what i want to say.
Apart from this, i found that you did’t use any encryption method, which is extremely wrong. Anyone can hack your password from the database.
You should use Password_verify() and Password_hash() functions to encrypt and decrypt your password. These encryption and decryption are considered most safe now days. You should not use md5 encryption because now days anyone can decrypt md5 algorithm.
Here i have made one tutorial Change password code in PHP. I have covered all the above topics. I Hope that this tutorial will help you.
Cheers,
answered Nov 8, 2015 at 13:49
1
Hello friends, I am back with another new tutorial for you. Today we will learn you about how to make a change password code in php. Do you think it is very hard? No, its just simple. You have seen in many application about change password functionality. This functionality is very useful while user forgot its password or want to change its current password. So i will not waste your time and go to the point. Let’s start…
Important for you: Email verification script using PHP and MySQL
Important for you: login logout using session in PHP example
Here we assume that we have one record in the database i.e. Email: [email protected], Password: abcd. Here password is stored in DB with password_hash() algorithm. Password_hash algorithm is consider as one of the best secure encryption algorithm. Remember that don’t use md5() encryption. md5() encryption is now not considered as a safest encryption.You can learn more about password_hash() and password_verify() from its official site.
What logic should be used?
Here we will use simple logic for change password code in PHP. In change password form, user will fill the information like old password, new password and confirm password. We will create a old password using password_verify function and match it with all email and password in database entries. Here you should remember that you have to store user’s email or userid in the session and use it for find out user who want to change its password. If we found any matched record then it will update their new password with password_hash encryption. We are not using email in this script but you can store it in session when user login and use it whenever needs.
Now see the below practical code. So you can understand more.
Create a change password html form with Javascript validation. Here is mine code. Please don’t copy it directly. First understand it and then practice it. If you have any problem while practice it then let me know in the comment box. I will help you to solve that problem.
style.css
.form-table { width:350px; margin-left: auto; margin-right: auto; } label{ font-weight: bold; } #form_submission_ajax{ background-color: #eee; padding-top: 10px; padding-bottom: 10px; } .error{ color: #ff0000; } input { border: 2px solid #531EBF; padding: 4px; } input[type="submit"] { padding: 5px 15px; background-color: #531EBF; border: 2px solid #531EBF; color: #fff; border-radius: 5px; } h1 { color: #531EBF; }
index.php
<!DOCTYPE html> <html> <head> <title>Change password in php</title> <link rel="stylesheet" type="text/css" href="style.css"> <script type="text/javascript" src="jquery-1.11.1.js"></script> </head> <body> <?php session_start(); $error = [ "old_password_error" => '', "new_password_error" => '', "confirm_password_error" => '' ]; $form_data = [ "old_password" => '', "new_password" => '', "confirm_password" => '' ]; if(!empty($_SESSION['error'])) { $error = $_SESSION['error']; } if(!empty($_SESSION['form_data'])) { $form_data = $_SESSION['form_data']; } ?> <h1><center>Change Password Form</center></h1> <form action="change-password.php" method="post" onsubmit="return validate();" id="form_submission_ajax"> <table class="form-table"> <tr> <td><label>Old password:</label></td> <td><input type="password" name="old_password" id="old_password" value="<?php echo $form_data['old_password']; ?>"></td> </tr> <tr> <td></td> <td id="old_password_error" class="error"><?php echo $error['old_password_error']; ?></td> </tr> <tr> <td><label>New Password:</label></td> <td><input type="password" name="new_password" id="new_password" value="<?php echo $form_data['new_password']; ?>"></td> </tr> <tr> <td></td> <td id="new_password_error" class="error"><?php echo $error['new_password_error']; ?></td> </tr> <tr> <td><label>Confirm Password:</label></td> <td><input type="password" name="confirm_password" id="confirm_password" value="<?php echo $form_data['confirm_password']; ?>"></td> </tr> <tr> <td></td> <td id="confirm_password_error" class="error"><?php echo $error['confirm_password_error']; ?></td> </tr> <tr> <td></td> <td> <input type="hidden" name="user_id" id="user_id" value="1"> <input type="submit" name="submit" value="Submit"> </td> </tr> </table> </form> </body> <script type="text/javascript"> function validate() { var valid = true; var old_password = $('#old_password').val(); var new_password = $('#new_password').val(); var confirm_password = $('#confirm_password').val(); if(old_password=='' || old_password==null) { valid=false; $('#old_password_error').html("* This field is required."); } else { $('#old_password_error').html(""); } if(new_password=='' || new_password==null) { valid=false; $('#new_password_error').html("* This field is required."); } else { $('#new_password_error').html(""); } if(confirm_password=='' || confirm_password==null) { valid=false; $('#confirm_password_error').html("* This field is required."); } else { $('#confirm_password_error').html(""); } if(new_password != '' && confirm_password != '') { if(new_password != confirm_password) { valid = false; $('#confirm_password_error').html("* Confirm password is same as new password."); } if(new_password == confirm_password) { $('#confirm_password_error').html(""); } } if(valid==true) { return true; } else { return false; } } </script> </html> <?php $_SESSION['error'] = ""; $_SESSION['form_data'] = ""; ?>
In the above form, there are three fields named old password, new password and confirm password. New password and current password will same. This form will validate using javascript before submit. So if user does not type confirm password same as new password then error established. Try that one 😉
Now here is a code for change a password using PHP on the server. We have also validate form data on the server side.
change-password.php
<?php session_start(); $email = "[email protected]"; $valid = true; $error = []; $form_data = []; if(!empty($_POST['old_password'])) { $old_password = $_POST['old_password']; $old_password_data = array("old_password" => $old_password); $form_data = array_merge($form_data, $old_password_data); $old_password_error = array("old_password_error" => ""); $error = array_merge($error, $old_password_error); } else { $valid = false; $old_password = ""; $old_password_data = array("old_password" => $old_password); $form_data = array_merge($form_data, $old_password_data); $old_password_error = array("old_password_error" => "* Old password is required."); $error = array_merge($error, $old_password_error); } if(!empty($_POST['new_password'])) { $new_password = $_POST['new_password']; $new_password_data = array("new_password" => $new_password); $form_data = array_merge($form_data, $new_password_data); $new_password_error = array("new_password_error" => ""); $error = array_merge($error, $new_password_error); } else { $valid = false; $new_password = ""; $new_password_data = array("new_password" => $new_password); $form_data = array_merge($form_data, $new_password_data); $new_password_error = array("new_password_error" => "* New password is required."); $error = array_merge($error, $new_password_error); } if(!empty($_POST['confirm_password'])) { $confirm_password = $_POST['confirm_password']; $confirm_password_data = array("confirm_password" => $confirm_password); $form_data = array_merge($form_data, $confirm_password_data); $confirm_password_error = array("confirm_password_error" => ""); $error = array_merge($error, $confirm_password_error); } else { $valid = false; $confirm_password = ""; $confirm_password_data = array("confirm_password" => $confirm_password); $form_data = array_merge($form_data, $confirm_password_data); $confirm_password_error = array("confirm_password_error" => "* Confirm password is required."); $error = array_merge($error, $confirm_password_error); } if($new_password != '' && $confirm_password != '') { if($new_password != $confirm_password) { $valid = false; $confirm_password_error = array("confirm_password_error" => "* Confirm password is same as new password."); $error = array_merge($error, $confirm_password_error); } if($new_password == $confirm_password) { $confirm_password_error = array("confirm_password_error" => ""); $error = array_merge($error, $confirm_password_error); } } if($valid==true) { include 'config.php'; mysqli_select_db($conn, $db_name); $check_data = "SELECT * FROM user_login WHERE email = '$email' "; $check_query = mysqli_query($conn, $check_data); $numRows = mysqli_num_rows($check_query); $user_data = mysqli_fetch_assoc($check_query); if($numRows == 1) { $check_old_password = password_verify($old_password,$user_data['password']); if($check_old_password) { $new_password_encrypt = password_hash($new_password,PASSWORD_DEFAULT); $user_id = $user_data['id']; $sql = "UPDATE user_login SET password = '$new_password_encrypt' WHERE id = '$user_id' "; $query = mysqli_query($conn, $sql); $row = mysqli_affected_rows($query); if($row == 1) { echo "Your password successfully changed."; die; } } else { echo "Opps, We can not find your data. Please try again."; die; } } else { echo "No database record matched with your data."; die; } } else { $_SESSION['error'] = $error; $_SESSION['form_data'] = $form_data; header('Location:index.php'); } ?>
All the data filled by user are on the server now. It’s time to validate them using php validation.
In the change password script we use server side validation using PHP. If form data does not satisfy the validation condition then script will redirect to “index.php” with errors. Otherwise password will change in the database.
I hope that you like this tutorial. Please share it with your friends. If you have any kind of problem regarding this tutorial then let me know in the comment box. I will help you to solve the problem. Thank you 🙂
In this tutorial I will explain how user can change their old password.First Create a html form with three fields.
Now Validate these fields with javascript. After this create a php script for change password . PHP script given below :
HTML code for Change Password Form
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<p style=«color:red;»><?php echo $_SESSION[‘msg1’];?><?php echo $_SESSION[‘msg1’]=«»;?></p> <form name=«chngpwd» action=«» method=«post» onSubmit=«return valid();»> <table align=«center»> <tr height=«50»> <td>Old Password :</td> <td><input type=«password» name=«opwd» id=«opwd»></td> </tr> <tr height=«50»> <td>New Passowrd :</td> <td><input type=«password» name=«npwd» id=«npwd»></td> </tr> <tr height=«50»> <td>Confirm Password :</td> <td><input type=«password» name=«cpwd» id=«cpwd»></td> </tr> <tr> <td><a href=«index.php»>Back to login Page</a></td> <td><input type=«submit» name=«Submit» value=«Change Passowrd» /></td> </tr> </table> </form> |
Javascript Validation for change Password
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
<script type=«text/javascript»> function valid() { if(document.chngpwd.opwd.value==«») { alert(«Old Password Filed is Empty !!»); document.chngpwd.opwd.focus(); return false; } else if(document.chngpwd.npwd.value==«») { alert(«New Password Filed is Empty !!»); document.chngpwd.npwd.focus(); return false; } else if(document.chngpwd.cpwd.value==«») { alert(«Confirm Password Filed is Empty !!»); document.chngpwd.cpwd.focus(); return false; } else if(document.chngpwd.npwd.value!= document.chngpwd.cpwd.value) { alert(«Password and Confirm Password Field do not match !!»); document.chngpwd.cpwd.focus(); return false; } return true; } </script> |
Script for Change Password
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<?php session_start(); include(«dbconnection.php»); if(isset($_POST[‘Submit’])) { $oldpass=md5($_POST[‘opwd’]); $useremail=$_SESSION[‘login’]; $newpassword=md5($_POST[‘npwd’]); $sql=mysqli_query($con,«SELECT password FROM userinfo where password=’$oldpass’ && email=’$useremail'»); $num=mysqli_fetch_array($sql); if($num>0) { $con=mysqli_query($con,«update userinfo set password=’ $newpassword’ where email=’$useremail'»); $_SESSION[‘msg1’]=«Password Changed Successfully !!»; } else { $_SESSION[‘msg1’]=«Old Password not match !!»; } } ?> |
Structure of userinfo Table
CREATE TABLE `userinfo` ( `id` int(11) NOT NULL, `email` varchar(255) NOT NULL, `password` varchar(250) NOT NULL, `updation_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=latin1; |
Download Source code(How to change Password in php)
Size: 209 KB
Version: V 2.0
How to run this script
1. Download and Unzip file on your local system.
2. Put this file inside root directory
3. Database Configuration
Database Configuration
Open phpmyadmin
Create Database test
Import database userinfo.sql (available inside zip package)
put this url in the browser http://localhost/changepassword
Login details
Username : admin@test.com
Password : Test@12345
В WordPress можно восстанавливать и изменять пароль пользователя, если у вас есть доступ к email пользователя или вы уже авторизованы. А как поменять (установить пароль) любому пользователю если вы не знаете пароль администратора? Ниже рассмотрим разные варианты изменения пароля для разных ситуаций.
Главное помните — всегда нужно указывать надежный пароль!
Узнать пароль пользователя WordPress невозможно, потому что пароли хранятся в БД в закодированном виде (в виде хэша) и единственный способ узнать пароль по хэшу — это его угадать. Такой подбор паролей называется Брут-форс.
Пароль хранится в базе данных в поле user_pass
таблицы wp_users
.
Авторизация — PHP
Чтобы не изменять пароль пользователя, но при этом попасть в админку, можно использовать функцию wp_set_auth_cookie().
Код ниже показывает как авторизоваться в качестве администратора не меняя его пароль.
Вставьте код в файл темы functions.php. Затем зайдите на любую страницу сайта и допишите в конец URL ?login_as_admin
. После этого вы автоматически будите авторизованы как администратор.
if( isset( $_GET['login_as_admin'] ) ){ add_action( 'init', function(){ $users = get_users( [ 'role' => 'administrator' ] ); wp_set_auth_cookie( $users[0]->ID ); } ); }
После использования этого кода, его обязательно нужно удалить!
Смена пароля — профиль в админке
Если вы авторизованы, то пароль можно изменить на странице профиля Пользователи → Ваш профиль
. Если вы при этом еще и администратор, то пароль можно изменить любому пользователю, перейдя в редактирование пользователя со страницы Пользователи → Все пользователи
.
Смена пароля — email (восстановление пароля)
Если вы забыли пароль, но у вас есть доступ к email пользователя, то пароль можно восстановить. Для этого нужно:
- Перейти на страницу Входа:
/wp-login.php
. - Кликнуть по ссылке «Забыли пароль?».
- Ввести email или имя пользователя, пароль для которого нужно восстановить.
- Перейти по ссылке на восстановление пароля, полученной на email (если указали имя пользователя, то нужно проверить email соответствующий имени пользователя).
- Ввести новый пароль в форме на которую вы попали кликнув по ссылке в письме.
- Войти на сайт используя новый пароль.
Смена пароля — phpMyAdmin
Почти все хостинг провайдеры предоставляют доступ к phpMyAdmin — панель управления базой данных.
Там установить пароль любого пользователя очень просто. Для этого нужно зайти в таблицу wp_users
и нажать «редактировать» (иконку карандаша) рядом с пользователем, пароль которого хотите поменять. В результате вы увидите такую форму:
Измените хэш код в поле user_pass
на новый пароль. И обязательно укажите MD5
для установленного значения (так введенный текстовый пароль будет захэширован и WP сможет его потом «распознать»).
Заметка: при первой авторизации MD5 хэш автоматически будет изменен на более надежный хэш, который используется в вашей версии WordPress.
Смена пароля — MySQL
Для установки нового пароля можно использовать SQL запрос.
Пример ниже, показывает как изменить пароль администратора WordPress, зная его логин. Тут новый пароль будет — newpass
, а логин администратора — admin
:
UPDATE wp_users SET user_pass = MD5('newpass') WHERE user_login = 'admin'
Если вдруг вы забыли логин, но точно помните, что вы были первым юзером на блоге, а значит ваш ID равен 1, то можно сбросить пароль по ID — WHERE ID = 1
:
UPDATE wp_users SET user_pass = MD5('newpass') WHERE ID = 1;
Или можно изменить пароль зная email юзера:
UPDATE wp_users SET user_pass = MD5('newpass') WHERE user_email = 'adminko@gmail.com';
MD5(‘newpass’) = e6053eb8d35e02ae40beeeacef203c1a
Пример запуска MySQL запроса из консоли
Для начала нужно зайти в консоль и подключиться к БД, такой командой:
mysql -u USERNAME -pPASSWORD -h HOST_NAME_OR_IP DATABASE_NAME
или без указания хоста (если вы работает в консоли из среды самого хостинга)
mysql -u USERNAME -pPASSWORD DATABASE_NAME
Далее, нужно запустить вышеупомянутый запрос, так:
mysql> UPDATE wp_users SET user_pass = MD5('newpass') WHERE user_login = 'admin';
Чтобы узнать название таблиц в базе данных my_database
, используйте команду:
mysql> SHOW TABLES IN my_database; +---------------------------+ | Tables_in_my_database | +---------------------------+ | wp_commentmeta | | wp_comments | | wp_options | | wp_postmeta | | wp_posts | | wp_term_relationships | | wp_term_taxonomy | | wp_termmeta | | wp_terms | | wp_usermeta | | wp_users | +---------------------------+
Чтобы получить список логинов пользователей из таблицы юзеров, используйте команду:
mysql> SELECT user_login FROM wp_users; +----------------+ | user_login | +----------------+ | abalak | | AbamFaw | | admin | +----------------+
Смена пароля — PHP
Новый пароль можно установить PHP кодом, с помощью функции wp_set_password().
Вставьте следующий код в файл темы functions.php. Затем зайдите на любую страницу сайта и допишите в конец URL ?init_new_pass_set=anton
.
В результате пароль пользователя anton
будет изменен на newpass
.
if( isset( $_GET['init_new_pass_set'] ) && $login = $_GET['init_new_pass_set'] ){ add_action( 'init', function() use ( $login ){ wp_set_password( 'newpass', get_user_by( 'login', $login )->ID ); wp_die( "Пароль юзера `$login` изменен" ); } ); }
После использования этого кода, его обязательно нужно удалить!
Смена пароля — WP-CLI
Установить пароль пользователя можно командой wp user update.
Этот пример показывает как для пользователя с логином USERNAME
установить пароль PASSWORD
:
wp user update USERNAME --user_pass="PASSWORD"
Получить список пользователей (чтобы узнать логин) можно командой wp user list:
wp user list +----+---------------+--------------+---------------------+---------------------+---------------+ | ID | user_login | display_name | user_email | user_registered | roles | +----+---------------+--------------+---------------------+---------------------+---------------+ | 4 | aleksej-nnn | Alex | alsey119@yandex.ru | 2018-04-24 21:04:24 | administrator | | 7 | denis | Denis | deis@denis.pro | 2018-06-06 23:30:54 | subscriber | | 9 | shk_user | shk_user | sheer@qsologies.com | 2018-08-11 13:27:09 | subscriber | | 8 | vladlu | vladlu | spata@famail.com | 2018-03-26 00:11:48 | editor | +----+---------------+--------------+---------------------+---------------------+---------------+
Сброс паролей — WP-CLI
Можно установить авто-сгенерированные пароли для указанных пользователей, для этого есть команда wp user reset-password.
Этот пример показывает как сбросить пароль для двух пользователей и отправить им сообщение о том что пароль был изменен.
wp user reset-password admin editor Reset password for admin. Reset password for editor. Success: Passwords reset.
Пользователь в результате получит такое сообщение на почту:
PikselZ 0 / 0 / 0 Регистрация: 02.05.2016 Сообщений: 11 |
||||
1 |
||||
Смена пароля пользователем05.06.2016, 22:21. Показов 4455. Ответов 11 Метки нет (Все метки)
Есть форма и php обработчик формы, для смены пароля пользователем после того как авторизируется, но я не знаю почему, пишет всегда ПОДТВЕРЖДЕНИЕ ПАРОЛЯ НЕ ВВЕДЕНО, уважаемые форумчане, будьте любезны подскажите новичку в php
__________________
0 |
Programming Эксперт 94731 / 64177 / 26122 Регистрация: 12.04.2006 Сообщений: 116,782 |
05.06.2016, 22:21 |
11 |
2165 / 1650 / 838 Регистрация: 10.01.2015 Сообщений: 5,184 |
|
05.06.2016, 22:32 |
2 |
PikselZ, отформатируйте код, как надо и ошибка сама выплывет.
0 |
Фрилансер 1846 / 1342 / 599 Регистрация: 12.01.2011 Сообщений: 5,429 |
|
05.06.2016, 22:32 |
3 |
md5
0 |
Пифагор 2165 / 1650 / 838 Регистрация: 10.01.2015 Сообщений: 5,184 |
||||||||
05.06.2016, 22:46 |
4 |
|||||||
Azdeman, благодарствую… Добавлено через 8 минут Добавлено через 5 минут
Может
?
0 |
Фрилансер 1846 / 1342 / 599 Регистрация: 12.01.2011 Сообщений: 5,429 |
|
05.06.2016, 22:49 |
5 |
md5 нормально работает. Не в нем дело…. я и не говорил что в нём.. я же ответил off специально, совет дал.
1 |
2165 / 1650 / 838 Регистрация: 10.01.2015 Сообщений: 5,184 |
|
05.06.2016, 22:57 |
6 |
А на оффсайте ничего не написано про его deprecated . Или он «морально» устарел??? Добавлено через 5 минут
0 |
Jodah |
05.06.2016, 23:35
|
Не по теме:
А на оффсайте ничего не написано про его deprecated. Или он «морально» устарел??? Ответ тут.
0 |
0 / 0 / 0 Регистрация: 02.05.2016 Сообщений: 11 |
|
06.06.2016, 00:21 [ТС] |
8 |
К сожалению нетт( так не помогло((((
0 |
Web Programmer 325 / 286 / 121 Регистрация: 28.09.2011 Сообщений: 1,570 |
|
06.06.2016, 00:59 |
9 |
PikselZ, А должно.
0 |
PikselZ 0 / 0 / 0 Регистрация: 02.05.2016 Сообщений: 11 |
||||
06.06.2016, 01:21 [ТС] |
10 |
|||
когда пишешь вот так
Выдаёт вот такую ошибку:
0 |
JimUSA Web Programmer 325 / 286 / 121 Регистрация: 28.09.2011 Сообщений: 1,570 |
||||||||
06.06.2016, 01:37 |
11 |
|||||||
PikselZ, Замените
на
0 |
PikselZ 0 / 0 / 0 Регистрация: 02.05.2016 Сообщений: 11 |
||||
06.06.2016, 02:38 [ТС] |
12 |
|||
Изменил, теперь пишет СТАРЫЙ ПАРОЛЬ НЕ ВЕРНЫЙ всегда Добавлено через 14 минут
0 |
I am working on a simple script that allows users to create an account. There is nothing special about it, at it asks for is a username, and password. The only problem I’m having is creating a script that allows the user to change their password. Here is my progress.
Its saying «Your current password is not right!», even though the password is fine. I already have it to connect to the database with another code on the same page.
<?php
$CurrentPassword = mysql_real_escape_string(strip_tags(stripslashes($_POST['CurrentPassword'])));
$NewPassword = mysql_real_escape_string(strip_tags(stripslashes($_POST['NewPassword'])));
$ConfirmNewPassword = mysql_real_escape_string(strip_tags(stripslashes($_POST['ConfirmNewPassword'])));
$Submit2 = mysql_real_escape_string(strip_tags(stripslashes($_POST['Submit2'])));
?>
<?php
if ($Submit2) {
$_OLDHASH = hash('sha512',''.$CurrentPassword.'');
$_NEWHASH = hash('sha512',''.$NewPassword.'');
$_CONFIRMNEWHASH = hash('sha512',''.$ConfirmNewPassword.'');
if ($myU->Password == $_OLDHASH) {
if ($_NEWHASH == $_CONFIRMNEWHASH) {
mysql_query("UPDATE Password='".$_NEWHASH."' WHERE Username='".$User."'");
session_destroy();
header("Location: index.php");
}
else {
echo "Your new password and new confirm password does not match!";
}
}
else {
echo "Your current password is not right!";
}
}
?>
<form action='' method='POST'>
<br />
Update Password
<br />
<input placeholder='Current Password' type='password' name='CurrentPassword'>
<br />
<input placeholder='New Password' type='password' name='NewPassword'>
<br />
<input placeholder='Confirm New Password' type='password' name='ConfirmNewPassword'>
<br />
<input type='submit' value='Change' name='Submit2'><br />
</form>
Mike
2,1143 gold badges20 silver badges33 bronze badges
asked Feb 20, 2013 at 21:05
15
When you check the password on login are you also doing all of this extraneous crap to it?
mysql_real_escape_string(strip_tags(stripslashes()))
Because I can see that causing issues with a password containing special characters, aka: a strong password. My advice is to not do that at all, you’re hashing the input before including it in the query, so there’s no chance of SQL injection with this particular field.
Other things wrong:
''.$NewPassword.''
is equivalent to simply$NewPassword
-
Why?
?> <?php
This will output a raw line break which is going to break your
header()
call.
answered Feb 20, 2013 at 21:14
SammitchSammitch
29k7 gold badges47 silver badges75 bronze badges
try to make two files:
changePass.html :
<form action='changePass.php' method='POST'>
<br />
Update Password
<br />
<input placeholder='Current Password' type='password' name='CurrentPassword'>
<br />
<input placeholder='New Password' type='password' name='NewPassword'>
<br />
<input placeholder='Confirm New Password' type='password' name='ConfirmNewPassword'>
<br />
<input type='submit' value='Change' name='Submit2'><br />
</form>
and second copyPass.php:
<?php
// Copy your php code here
?>
So, when user wants to change pass, point him to changePass.html, and when he enters the form, data will be transmited and processed to changePass.php. Please notice that in form tag / action parameter is added changePass.php as webpage which will process data.
Now I also noticed wrong syntax in your SQL query, you should write something like:
mysql_query(«UPDATE passwordTable
SET
Password='».$_NEWHASH.»‘ WHERE Username='».$User.»‘»);
answered Feb 20, 2013 at 21:14
I am working on a simple script that allows users to create an account. There is nothing special about it, at it asks for is a username, and password. The only problem I’m having is creating a script that allows the user to change their password. Here is my progress.
Its saying «Your current password is not right!», even though the password is fine. I already have it to connect to the database with another code on the same page.
<?php
$CurrentPassword = mysql_real_escape_string(strip_tags(stripslashes($_POST['CurrentPassword'])));
$NewPassword = mysql_real_escape_string(strip_tags(stripslashes($_POST['NewPassword'])));
$ConfirmNewPassword = mysql_real_escape_string(strip_tags(stripslashes($_POST['ConfirmNewPassword'])));
$Submit2 = mysql_real_escape_string(strip_tags(stripslashes($_POST['Submit2'])));
?>
<?php
if ($Submit2) {
$_OLDHASH = hash('sha512',''.$CurrentPassword.'');
$_NEWHASH = hash('sha512',''.$NewPassword.'');
$_CONFIRMNEWHASH = hash('sha512',''.$ConfirmNewPassword.'');
if ($myU->Password == $_OLDHASH) {
if ($_NEWHASH == $_CONFIRMNEWHASH) {
mysql_query("UPDATE Password='".$_NEWHASH."' WHERE Username='".$User."'");
session_destroy();
header("Location: index.php");
}
else {
echo "Your new password and new confirm password does not match!";
}
}
else {
echo "Your current password is not right!";
}
}
?>
<form action='' method='POST'>
<br />
Update Password
<br />
<input placeholder='Current Password' type='password' name='CurrentPassword'>
<br />
<input placeholder='New Password' type='password' name='NewPassword'>
<br />
<input placeholder='Confirm New Password' type='password' name='ConfirmNewPassword'>
<br />
<input type='submit' value='Change' name='Submit2'><br />
</form>
Mike
2,1143 gold badges20 silver badges33 bronze badges
asked Feb 20, 2013 at 21:05
15
When you check the password on login are you also doing all of this extraneous crap to it?
mysql_real_escape_string(strip_tags(stripslashes()))
Because I can see that causing issues with a password containing special characters, aka: a strong password. My advice is to not do that at all, you’re hashing the input before including it in the query, so there’s no chance of SQL injection with this particular field.
Other things wrong:
''.$NewPassword.''
is equivalent to simply$NewPassword
-
Why?
?> <?php
This will output a raw line break which is going to break your
header()
call.
answered Feb 20, 2013 at 21:14
SammitchSammitch
29k7 gold badges47 silver badges75 bronze badges
try to make two files:
changePass.html :
<form action='changePass.php' method='POST'>
<br />
Update Password
<br />
<input placeholder='Current Password' type='password' name='CurrentPassword'>
<br />
<input placeholder='New Password' type='password' name='NewPassword'>
<br />
<input placeholder='Confirm New Password' type='password' name='ConfirmNewPassword'>
<br />
<input type='submit' value='Change' name='Submit2'><br />
</form>
and second copyPass.php:
<?php
// Copy your php code here
?>
So, when user wants to change pass, point him to changePass.html, and when he enters the form, data will be transmited and processed to changePass.php. Please notice that in form tag / action parameter is added changePass.php as webpage which will process data.
Now I also noticed wrong syntax in your SQL query, you should write something like:
mysql_query(«UPDATE passwordTable
SET
Password='».$_NEWHASH.»‘ WHERE Username='».$User.»‘»);
answered Feb 20, 2013 at 21:14