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>
Related
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";
}
I am new to CodeIgniter, and am trying to write code to log in after registering using a username and password in registration form using a PHPMyAdmin database. I am not getting anything when I try to log in, and it doesn't display an error or any message.
public function login() {
$this->form_validation->set_rules('username','Username','required');
$this->form_validation->set_rules('password' , 'Password');
if($this->form_validation->run() == TRUE){
//check user in database
$this->db->select('username' , 'password');
$this->db->from('user_register');
$this->db->where(array('username' => $username, 'password' => $password));
$query = $this->db->get();
$user = $query->row();
if($user->email){
$this->session->set_flashdata("Successful login");
$_SESSION['user_logged'] = TRUE;
$_SESSION['username'] = $user->username;
} else {
$this->session->set_flashdata("Error No such record found");
}
}
// load view and showing login form
$this->load->view('login');
}
First, you should read the documentation, looks like you skip that part, but it's very important!
Let's code a little bit and fix the bugs!
User data
Well, users will enter their data and we will check, if evertyhing is correct, we can redirect user to the protected page. You call for variables (see Query:) but you I'm not seeing on your code. You should put like that, before your query job
$username = $this->input->post("username");
$password = $this->input->post("password");
Now, you will be able to use the where to get the user data. =)
Query:
If read about OOP with PHP, you know that when you pass parameters to a method, each parameter have their own "action". In case of the select method, you should keep the data you want to select, on the same quote, because you the way you do, it's like you passing multiple parameters to the method.
$this->db->select('username, password');
$this->db->from('user_register');
$this->db->where(array('username' => $username, 'password' => $password));
First, to decide if the record exist or not, I prefer this way:
if($query->num_rows() > 0) {
$user_data = $query->row();
// We should verify if the user entered the password that correspond to the account.
// If not, we tell them that the password is incorrect.
if($password != $user_data->password) {
$this->session->set_flashdata("error", "Wrong password!");
return redirect(site_url());
}
// You can use the CI built in methods to work with sessions
$this->session->set_userdata(array(
'username' => $user_data->username,
));
$this->session->set_flashdata("success", "You are logged in!");
return redirect(site_url());
} else {
$this->session->set_flashdata("Error: No such record found");
redirect(site_url());
}
Flash data
Yeah, we use flashdata to show a message for the user. But, you should pass an item and the value of this item. Like that:
$this->session->set_flashdata('success', 'Successfully logged in!");
And, to retrieve the data on your views, you can do like...
<?php
$success = $this->session->flashdata("success");
$error = $this->session->flashdata("error");
if(!empty($success)) {
echo $success;
}
if(!empty($success)) {
echo $error;
}
?>
Recommendations
Sessions: https://codeigniter.com/userguide3/libraries/sessions.html
Database: https://www.codeigniter.com/userguide3/database/query_builder.html
Also, I recommed you, to take a minute on YouTube, to understand CodeIgniter.
If I forgot something, let me know! =)
Great Suggestion by webmasterdro's Answer.
I would like to extend it a little bit.
Looking at your code it looks like you have added the query to the controller.
And as a suggestion, if you are using an MVC framework then try to follow some basic MVC flow. because if you are not following that then it will be useless to use a framework.
User Controller to handle the post data and validations.
Use model to do the database query.
Use __construct for loading the common model or libraries.
Do not save plane password use md5 or other encryption technique.
Store User detail to the session which you can use further in after login.
Codeigniter has a great user guide. Try to follow that.
So, your code Should be your like this below.
Controller:
public function __construct() {
parent::__construct();
// Load model
$this->load->model('login_database');
}
public function your_controller_function_name() {
// Check validation for user input in SignUp form
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
if ($this->form_validation->run() == FALSE) {
$this->load->view('login_form_view');
} else {
$username = $this->input->post("username");
$password = $this->input->post("password");
$result = $this->login_database->registration_insert($username, $password);
//You can do this also if($result != FALSE)
if (!empty($result)) {
// You can set other data to the session also form here
$session_data = array(
'username' => $result['user_name']
);
// Add user data in session
$this->session->set_userdata('logged_in', $session_data);
// You can set flash data here
$this->load->view('your_view');
} else {
$data = array(
'error_message' => 'Invalid Username or Password'
);
$this->load->view('your_login_form_view', $data);
}
}
}
Model:
// Read data using username and password
public function login($username, $password) {
$this->db->select('username');
$this->db->from('user_register');
$this->db->where(array('username' => $username, 'password' => $password));
$query = $this->db->get();
$user_data = $query->row_array();
if ($query->num_rows() == 1) {
return user_data;
} else {
return false;
}
}
I have not added detail related to flash data because the previous answer has explained it properly.
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;
}
}