What is wrong with this code? Even I enter a correct password still it returns "Old password is incorrect".
I also tried $hash = Yii::$app->getSecurity->generatePasswordHash($current_password_textbox);
function actionUpdate_password() {
$current_password_textbox = filter_input(INPUT_POST, 'current_password');
$new_password = filter_input(INPUT_POST, 'new_password');
$current_account = \app\models\Users::findOne(yii::$app->user->identity->id);
$current_hash__from_db = $current_account->password_hash;
$hash = Yii::$app->getSecurity->generatePasswordHash($current_password_textbox);
//$hash = Yii::$app->security()->generatePasswordHash($current_password);
if (Yii::$app->getSecurity()->validatePassword($current_hash__from_db, $hash)) {
echo " all good, proceed to changing password";
} else {
echo "Old password is incorrect";
}
}
You shouldn't generate a hash from the input password. You only pass it to validatePassword() function. For example:
$password = 'testpass';
$hash = Yii::$app->getSecurity()->generatePasswordHash($password);
if (Yii::$app->getSecurity()->validatePassword($password, $hash)) {
echo 'correct password';
} else {
echo 'incorrect password'
}
In your case logic might look like:
$current_password_textbox = filter_input(INPUT_POST, 'current_password');
$current_account = \app\models\Users::findOne(yii::$app->user->identity->id);
if (!is_null($currenct_account) && Yii::$app->getSecurity()->validatePassword($current_password_textbox, $current_account->password_hash)) {
echo " all good, proceed to changing password";
} else {
echo "Old password is incorrect";
}
Related
Am using drupal to manage my content. I want to search all my contents title and body and find how many times each word is repeated in the whole contents.
It may be by an sql query, but I have no experience with sql.
Any ideas?
This code searches the body field and ALL fields of ANY Content Types for a specific string. You can run it via command line. Say you save it as "fieldsearch.php", you can then run it as:
php fieldsearch.php "myStringForWhichToSearch"
You need to fill in your connection data and database name. It outputs the array of matching nodes but you can format that output into anything you'd like (I recommend csv).
<?php
//Set Parameters here
$env = "dev"; // Options [dev|prod] - Defaults to dev
$prodConnection = array(
"host" => "",
"user" => "",
"pass" => ""
);
$devConnection = array(
"host" => "",
"user" => "",
"pass" => ""
);
//Use the selected env settings
if($env == "prod"){
$connection = $prodConnection;
} else {
$connection = $devConnection;
}
function getTables($con, $database){
//Get the set of field tables
$sql = "SHOW TABLES FROM $database";
$result = mysqli_query($con, $sql);
if (!$result) {
echo "DB Error, could not list tables\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
$tables = array();
while ($row = mysqli_fetch_row($result)) {
$tables[] = $row[0];
}
mysqli_free_result($result);
return $tables;
}
function getFieldTables($con,$database){
$allTables = getTables($con, $database);
$fieldTables = array();
foreach($allTables as $key => $table){
if( isFieldTable($table) ){
$fieldTables[] = $table;
}
}
//add the common tables
$fieldTables[] = "field_data_body";
$fieldTables[] = "field_data_comment_body";
return $fieldTables;
}
function isFieldTable($table){
//echo $table . "\n";
if( stripos($table, "field_data_field") !== FALSE){
return TRUE;
}
}
//Set the search term here:
if (array_key_exists(1, $argv)) {
$searchString = $argv[1];
}
else {
die('usage: php fieldsearch.php "search string"' . "\n");
}
$databaseName = "myDatabaseName";
$outArray = array();
//Connect
$con=mysqli_connect($connection['host'],$connection['user'],$connection['pass'],$databasePrefix.$databaseNum);
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//getFieldTables
$fieldTables = getFieldTables($con, $databaseName);
//Query each field tables data for the string in question
foreach($fieldTables as $key => $table){
//get Field value column name
$valueCol = str_replace("field_data_field_", '', $table);
$result = mysqli_query($con,"SELECT
entity_id
FROM
$table
WHERE
field_" . $valueCol . "_value
LIKE
'%$searchString%';");
if($result){
while($row = mysqli_fetch_assoc($result)){
$dataArray[$table][$row['entity_id']]['nid'] = $row['entity_id'];
}
}
}
//Add the body table
$result = mysqli_query($con,"SELECT
entity_id
FROM
field_data_body
WHERE
body_value
LIKE
'%$searchString%';");
if($result){
while($row = mysqli_fetch_assoc($result)){
$dataArray['field_data_body'][$row['entity_id']]['nid'] = $row['entity_id'];
}
}
var_dump($dataArray);
i have made form by Codeigniter to reset password when i send request it return with tis error
ou have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '#hotmail.com' at line 1.
this is my controller
function index()
{
$this->load->model("user_model");
$config['protocol'] = 'smtp';
$config['smtp_host'] = 'ssl://abuqir.net';
$config['smtp_port'] = '465';
$config['smtp_timeout'] = '7';
$config['smtp_user'] = 'myuser';
$config['smtp_pass'] = 'mypass';
$config['charset'] = 'utf-8';
$config['newline'] = "\r\n";
$config['mailtype'] = 'text'; // or html
$config['validation'] = TRUE; // bool whether to validate email or not
$email_to = $this->input->get('email');
$pass_message = $this->user_model->get_pass($email_to);
$this->email->initialize($config);
$this->email->from('admin-team#abuqir.net', 'admin team');
$this->email->to($email_to);
$this->email->subject('Reset password');
$this->email->message($pass_message);
$this->email->send();
echo $this->email->print_debugger();
$this->load->view('email_view');
}
and this my model
public function get_pass($user_mail) {
$user_mail = mysqli_real_escape_string($user_mail);
$query = $this->db->query('SELECT password'
. ' from users '
. 'where email = '.$user_mail
);
return $query;
}
In Model
public function get_pass($user_mail)
{
$user_mail = mysqli_real_escape_string($user_mail);
$query = $this->db->query("SELECT password from users where email = '$user_mail'");
$result = $query->result_array();
return $result;
}
In Controller
function index()
{
$email_to = $this->input->post('email'); //check GET otr POST
$pass_message = $this->user_model->get_pass($email_to);
if(!empty($pass_message))
{
$this->load->model("user_model");
$config['protocol'] = 'smtp';
$config['smtp_host'] = 'ssl://abuqir.net';
$config['smtp_port'] = '465';
$config['smtp_timeout'] = '7';
$config['smtp_user'] = 'myuser';
$config['smtp_pass'] = 'mypass';
$config['charset'] = 'utf-8';
$config['newline'] = "\r\n";
$config['mailtype'] = 'text'; // or html
$config['validation'] = TRUE; // bool whether to validate email or not
$this->email->initialize($config);
$this->email->from('admin-team#abuqir.net', 'admin team');
$this->email->to($email_to);
$this->email->subject('Reset password');
$this->email->message($pass_message[0]['password']);
if(! $this->email->send())
{
echo $this->email->print_debugger();
}
else
{
//Email sending failed
$this->load->view('email_view');
}
}
else
{
// Successfully sent
echo 'Invalid E-Mail Address'
}
}
Before configure mail check email validity then do rest of code
When you use $this->input->post it will act as mysqli_real_escape_string too. For further you need to secure from XSS use boolean TRUE. ($this->input->post('some_data', TRUE);)
public function get_pass($user_mail) {
$user_mail = mysqli_real_escape_string($user_mail);
$query = $this->db->query('SELECT password'
. ' from users '
. "where email = '".$user_mail ."'"
);
return $query;
}
You forgot to wrapper email in Query within single quotes.
NOTE: I am not sure how we build Parameter query using CodeIgnitor, please use that as this query is seriously unsafe and been a password reset query, it is probably more public code and not recommended.
Iam using the php 5.5 and pdo to create login code. the code is working fine but the only first user is loged in I don't know why? for example I have 5 user in my database table. when I login the first one then it goes to logedin but when I try to login the 2nd or 3rd one then it will show an error message which I set on incorrect data login. Below is my login code...
<?php
session_start();
include 'conn.php';
try
{
$user = $_POST['user'];
$pass = $_POST['pass'];
$remember=$_POST['remember'];
$smt=$conn->prepare("SELECT * FROM signup");
$smt->execute();
$result=$smt->fetch(PDO::FETCH_OBJ);
$prev=$result->Password;
$usr=$result->Username;
if(password_verify($pass,$prev)& $user===$usr)
{
// Set username session variable
$_SESSION['user'] = $user;
// Jump to secured page
header('location:index.php');
}
else
{
header('location:signin.php');
$_SESSION['login']="Incorrect username or password";
}
if($remember)
{
setcookie('remember-me',$user,time()+3600000);
setcookie('remember-pass',$pass,time()+3600000);
header('location:index.php');
}
else
{
setcookie('remember-me',$user,false);
setcookie('remember-pass',$pass,false);
}
}
catch(PDOException $e)
{
throw new PDOException($e);
}
?>
Thanks in advance...
You are missing a WHERE CLAUSE :
SELECT * FROM signup WHERE Username = :user
adjust your code to the following:
$smt=$conn->prepare("SELECT * FROM signup WHERE Username =:user");
$smt->execute(array(':user'=>$user));
Please update your code with below code
<?php
session_start();
include 'conn.php';
try
{
$user = $_POST['user'];
$pass = $_POST['pass'];
$remember=$_POST['remember'];
$smt=$conn->prepare("SELECT * FROM signup WHERE username = '".$user."' AND password = '".$pass."' ");
$smt->execute();
$result=$smt->fetch(PDO::FETCH_OBJ);
$prev=$result->Password;
$usr=$result->Username;
if(password_verify($pass,$prev)& $user===$usr)
{
// Set username session variable
$_SESSION['user'] = $user;
// Jump to secured page
header('location:index.php');
}
else
{
header('location:signin.php');
$_SESSION['login']="Incorrect username or password";
}
if($remember)
{
setcookie('remember-me',$user,time()+3600000);
setcookie('remember-pass',$pass,time()+3600000);
header('location:index.php');
}
else
{
setcookie('remember-me',$user,false);
setcookie('remember-pass',$pass,false);
}
}
catch(PDOException $e)
{
throw new PDOException($e);
}
?>
I have a database with aproximately 200 tables. I want to clone a certain user-account in this database. Is this possible in mysql?
With cloning I mean to create a new user with the same 'settings' as the user with id 14.
A quick google search reveals that you in fact can do this. There is a utility called " "mysql user clone", that lets you surprisingly clone a user for mysql.
If you check out the manual I'm sure it provides you with great tips about how to use it, for instance, this quote:
EXAMPLES
To clone joe as sam and sally with passwords and logging in as root on the local machine, use this command:
$ mysqluserclone --source=root#localhost \
--destination=root#localhost \
joe#localhost sam:secret1#localhost sally:secret2#localhost
# Source on localhost: ... connected.
# Destination on localhost: ... connected.
# Cloning 2 users...
# Cloning joe#localhost to user sam:secret1#localhost
# Cloning joe#localhost to user sally:secret2#localhost
# ...done.
since it appears #Nanne's approach, mysqluserclone is EOL / not supported by Oracle, i wrote a similar utility in PHP, usage:
<?php
$db = new \PDO("mysql:host={$db_creds->dbhost};dbname={$db_creds->dbname};charset=utf8mb4;port=" . $db_creds->dbport, $db_creds->superuser_user, $db_creds->superuser_pass, array(
\PDO::ATTR_EMULATE_PREPARES => false,
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC
));
Mysqluserclone::clone_account($db, "original username", "cloned username");
and this part of the code may be of particular interest:
if (0) {
echo "the following SQLs will clone this account:\n";
echo implode("\n\n", $sqls_for_cloning) . "\n\n";
die();
}
<?php
class Mysqluserclone{
private function __construct(){
// by making this private, we ensure nobody try to instantiate us.
}
public static function clone_account(\PDO $db_connected_as_superuser, string $original_name, string $clone_name): void
{
$db = $db_connected_as_superuser;
$sqls_for_cloning = [];
$sql = "SELECT COUNT(*) FROM mysql.user WHERE User = " . $db->quote($clone_name);
if (0 !== $db->query($sql)->fetch(\PDO::FETCH_NUM)[0]) {
throw new \InvalidArgumentException("clone name already exists!");
}
$sql = "SELECT * FROM mysql.user WHERE User = " . $db->quote($original_name);
$current_user_one_for_each_host = $db->query($sql)->fetchAll(\PDO::FETCH_ASSOC);
foreach ($current_user_one_for_each_host as $user_record) {
$user_record["User"] = $clone_name;
$sql = "INSERT INTO mysql.user SET \n";
foreach ($user_record as $name => $val) {
$sql .= self::mysql_quote_identifier($name) . " = " . self::mysql_quote_better($db, $val) . ",\n";
}
if (! empty($user_record)) {
$sql = substr($sql, 0, - strlen(",\n"));
}
$sql .= ";";
$sqls_for_cloning[] = $sql;
$sqls_for_cloning[] = "FLUSH PRIVILEGES;"; // YES this is required, otherwise you might get "grant not allowed to create accounts" errors
$grants_raw_sql = 'SHOW GRANTS FOR ' . $db->quote($original_name) . '#' . $db->quote($user_record['Host']) . ";";
try {
$grants_raw = $db->query($grants_raw_sql)->fetchAll(\PDO::FETCH_NUM);
} catch (\Throwable $ex) {
// somehow an empty grant table is a mysql error, not an empty rowset.. ignore it.
$grants_raw = [];
}
$grants_raw = array_map(function (array $arr): string {
if (count($arr) !== 1) {
throw new \LogicException("mysql layout for SHOW GRANTS has changed? investigate");
}
return $arr[0];
}, $grants_raw);
$original_name_as_identifier = self::mysql_quote_identifier($original_name);
$clone_name_as_identifier = self::mysql_quote_identifier($clone_name);
foreach ($grants_raw as $grant) {
if (false === strpos($grant, $original_name_as_identifier)) {
throw new \LogicException("original grant without original name as identifier? investigate");
}
$grant = self::str_replace_last($original_name_as_identifier, $clone_name_as_identifier, $grant);
$grant .= ";";
$sqls_for_cloning[] = $grant;
}
}
if (! empty($sqls_for_cloning)) {
$sqls_for_cloning[] = "FLUSH PRIVILEGES;";
}
if (0) {
echo "the following SQLs will clone this account:\n";
echo implode("\n\n", $sqls_for_cloning) . "\n\n";
die();
}
foreach ($sqls_for_cloning as $clone_sql) {
$db->exec($clone_sql);
}
}
private static function mysql_quote_identifier(string $identifier): string
{
return '`' . strtr($identifier, [
'`' => '``'
]) . '`';
}
private static function mysql_quote_better(\PDO $db, $value): string
{
if (is_null($value)) {
return "NULL";
}
if (is_int($value)) {
return (string) $value;
}
if (is_float($value)) {
return number_format($value, 10, '.', '');
}
if (is_bool($value)) {
return ($value ? "1" : "0");
}
return $db->quote($value);
}
private static function str_replace_last(string $search, string $replace, string $subject): string
{
$pos = strrpos($subject, $search);
if ($pos !== false) {
$subject = substr_replace($subject, $replace, $pos, strlen($search));
}
return $subject;
}
}
I've tried and tried creating a form to change your password, but I can't seem to get it right, please help! It is now telling me that "Query failed" each time I try to change the password, there are other variables such as username, first name that are involved however the user is only allowed to change their password so I had only included UPDATE members SET 'passwd' -- These are the variables created when someone initially registers, members(firstname, username, login, passwd, ip) VALUES('$fname','$uname','$login','".md5($_POST['password'])."','$ip')";
<?php
require_once('config.php');
require_once('auth.php');
//Array to store validation errors
$errmsg_arr = array();
//Validation error flag
$errflag = false;
//Connect to mysql server
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
//Select database
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}
//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
$str = #trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
//Sanitize the POST values
$password = clean($_POST['password']);
$retpassword = clean($_POST['retpassword']);
//Input Validations
if($password == '') {
$errmsg_arr[] = 'Password missing';
$errflag = true;
}
if($retpassword == '') {
$errmsg_arr[] = 'Please retype your password';
$errflag = true;
}
if( strcmp($password, $retpassword) != 0 ) {
$errmsg_arr[] = 'New passwords do not match!';
$errflag = true;
}
//If there are input validations, redirect back to the settings page
if($errflag) {
$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
session_write_close();
header("location: settings.php");
exit();
}
//Create UPDATE query
$qry = "UPDATE members SET 'passwd' = '".md5($_POST['password'])."' WHERE login = '{$_SESSION['username']}'";
$result = #mysql_query($qry);
//Check whether the query was successful or not
if($result) {
header("location: changed.php");
exit();
}else {
die("Query failed");
}
?>
This probably has to do more with the form you use to send the data.
Check the form method="POST" and check the names on your input fields.
Your form should look like this to be working with your PHP code
<form method="POST">
<input type="password" name="password">
<input type="password" name="retpassword">
</form>