Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I am currently developing a Document Authentication System and I want the Passwords of the users to be hashed or encrypted ..
So my question is, what is the best and most secure TWO WAY Hashing or Encrypting method I will use ..
As it has been suggested in the comments above the best and easy way is to use password_hash(); and password_verify(); more info is available in the php.net website, and also make use of prepared statements either with mysqli or pdo in my basic user registration i made use of PDO.
Please not this is just a basic example of how to use password_hash and password_verify();
we will use the password_hash() upon registration and password_verify() upon login
db.php
<?php
$server="localhost";
$username="root";
$password="";
try{
$dbh = new PDO("mysql:host=$server;dbname=sytemDb",$username,$password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $exc){
error_log($exc);
}
?>
The above script makes connection to our database.
register.php
<?php
include 'db.php';
$errors="";
if (isset($_POST['register'])) {
//check if values are not empty
if(empty($_POST['email'])){
die("please enter email");
$errors++;
}else{
$email = $_POST['email'];
//then check for valid email
}
}
if(empty($_POST['upass'])){
die("enter password");
$errors++;
}else{
$password = $_POST['upass'];
$hash = password_hash($password,PASSWORD_DEFAULT);//hashing password
}
if($errors <=0){
//no errors save to db
$stmt= $dbh->prepare("INSERT INTO users (username,password) VALUES(?,?)");
$stmt->execute(array($username,$hash));
echo "User registered";
}
?>
<!DOCTYPE html>
<html>
<head>
<title>User Registration</title>
</head>
<body>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<input type="email" name="email" placeholder="Ente Username">
<input type="password" name="upass" placeholder="Enter Password">
<button type="submit" name="register">Register</button>
</form>
</body>
</html>
Login.php
<?php
ob_start();
session_start();
include 'db.php';
if(isset($_POST['login'])){
if(empty($_POST['username']) || empty($_POST['pass'])){
die("enter password or username");
}else{
$uname = $_POST['username'];
$password = $_POST['pass'];
}
try {
$stmt = $dbh->prepare("SELECT userid,password,username from users where username = ?");
$stmt->bindValue(1,$uname);
$stmt->execute();
$results = $stmt->fetchall(PDO::FETCH_ASSOC);
if(count($results) > 0){
//if username is correct continue check entered password against saved hash
foreach ($results as $row) {
if(password_verify($password,$row['password'])){
//password and saved hash match go to dashboard
echo "login success";
$_SESSION['user']= $row['userid'];
header("refresh:5;url=dashboard");
}else{
echo "username and password does not match";
}
}
}else{
echo "username and password does not match";
}
} catch (PDOException $e) {
error_log($e);
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<form method="POST" action="">
<input type="text" name="username" placeholder="Enter username">
<input type="password" name="pass" placeholder="Enter password">
<button type="submit" name="login">Login</button>
</form>
</body>
</html>
This should do its very basic password hash is available in the manual here and here
password_verify() also available here
Please make use of php 5.6 or above of which u were supposed to already do.
That's about it. Hope this will point you to the correct direction.
NB: Always verify input from the user, don't forget to filter and
sanitize the input then prepare a statement to save to the db.
incase a user forget a password, well there are many ways to reset the user password, one basic way is to have an autho token column on ur db.
The following way is very basic for beginners just to kickoff your career lol ;)
<?php
function ForgetPassword()
{
try {
//search the user on the database
$stmt = $dbh->prepare("SELECT email,userid,firstname,lastname from users where email = ?");
$stmt->bindvalue($email);
$stmt->execute();
$results = $stmt->fetchall(PDO::FETCH_ASSOC);
if (count($results) > 0) { //user found generate authentication token
foreach ($results as $row):
$userid = base64_encode($row['userID']);
$randomAuth = md5(uniqid(rand()));
$dataUpdate = $dbh->prepare("UPDATE users set auth_token = ? where email = ?");
$dataUpdate->execute(array(
$randomAuth,
$row['email']
));
//send reset link to the user
$link = "Reset your password";
$header = "MIME-Version: 1.0" . "\r\n";
$header .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$header .= 'From: <>' . "\r\n";
$message = "<p> Hello " . $row['firstname'] . " " . $row['lastname'] . "</p>";
$message .= "<p> You have requested to reset your password your password</p>";
$message .= "<p>" . $link . "</p>";
if (mail(($row['email']), "Password Reset", $message, $header)) {
$successMessage = "Reset link sent to the provided email address";
} else {
error_log("cound not send message");
}
endforeach;
} else {
$successMessage = "Reset link sent to the provided email address";
}
}
catch (PDOException $ex) {
error_log($ex);
}
}
?>
Then reset passwordpage
<?php
function resetPassword()
{
if (isset($_GET['code']) && isset($_GET['token'])) {
$code = base64_decode($_GET['code']);
$token = $_GET['token'];
if (isset($_POST['resetpassword'])) {
//check empty fields
if (empty($_POST['newpassword'])) {
$errorMessage = "enter password";
$errors++;
return $errorMessage;
} else {
$password = $_POST['newpassword'];
$hash = password_hash($password, PASSWORD_DEFAULT); //password encryption
}
if (!empty($_POST['newpassword']) && empty($_POST['confirmpassword'])) {
$errorMessage = "Please confirm your password";
$errors++;
return $errorMessage();
}
if (!empty($_POST['confirmpassword']) && $_POST['confirmpassword'] !== $_POST['newpassword']) {
return "Passwords does not match";
$errors++;
}
}
if ($errors <= 0) {
try {
$stmt = $dbh->prepare("Update users set password = ? where userID = ? AND auth_token = ?");
$stmt->execute(array(
$hash,
$code,
$token
));
return "Password successfully changed.. Redirecting to login page";
$update = $dbh->prepare("UPDATE users set aut_token = NULL where userID = ? ");
$update->bindValue(1, $code);
$update->execute();
header("refresh=3:url;login");
}
catch (PDOException $e) {
error_log($e->getMessage());
}
}
} else {
//token code error
return "The link have expired, please go back and request a new one";
}
}
?>
Related
I have a script that adds an email address and password to a table. I first search to see if the email address exists in the table. If it does, I give an error message. If it does not, I add the record.
Then, using mysqli_insert_id(), I run another query to update the record I just added, encrypting the password with md5.
But every time I run it, the record is added, but the password does not get updated with the md5 version of the password. I have echo'd the query and it shows that it should be updating the password with the encryption, but it doesn't. Any ideas?
<?php
session_start();
error_reporting(E_ALL);
if (array_key_exists("submit", $_POST)) {
$link = mysqli_connect("localhost", "eits_Admin", "WebSpinner1", "EITS_Sandbox");
if (!$link) {
die("Database connection error");
}
$error = '';
if (!$_POST['email']) {
$error .= "<br/>An email address is required";
}
if (!$_POST['password']) {
$error .= "<br/>A password is required";
}
if ($error != "") {
$error = "There were errors in your form - ".$error;
} else {
$query = "select id from secretdiary
where email = '".mysqli_real_escape_string($link, $_POST['email'])
."' limit 1";
// echo $query;
$result = mysqli_query($link, $query);
if (mysqli_num_rows($result) > 0) {
$error = "That email address is not available.";
} else {
$query = "insert into secretdiary
(email,password)
values ('" . mysqli_real_escape_string($link, $_POST['email'])
. "', '"
. mysqli_real_escape_string($link, $_POST['password']) . "')";
if (!mysqli_query($link, $query)) {
$error = "Could not sign you up at this time. Please try again later.";
} else {
$encPass = md5(md5(mysqli_insert_id($link)) . $_POST['password']);
$query = "update secretdiary
set password = '" . $encPass
. "' where id = " . mysqli_insert_id($link) . " limit 1";
echo $query;
$result = mysqli_query($link,$query);
echo "Sign up successful.";
}
}
}
}
?>
<div id="error"><? echo $error; ?></div>
<form method="post">
<input type="email" name="email" placeholder= "Your Email">
<input type="password" name="password" placeholder="Password">
<input type="checkbox" name="stayLoggedIn" value=1>
<input type="submit" name="submit" value="Sign Up!">
</form>
You've got a lot of lines of code for a relatively simple process. Personally your form error handling such as if it's empty (in this case) can be remedied by adding required at the end of each HTML form input element (This is what I'd do)
Secondly, md5 isn't safe for hashing passwords (you're hashing a password not encrypting it)
Thirdly here's a way to hash the password from the form using Bcrypt which is much better than using md5 hashing. So do whatever error checking you need to do before like counting the usernames and if row > 0 die('username exists) Example of full code at base using PDO
When checking the users login simply use password_verify() function to do so
Tidy code helps people on SO understand what your problem is and is generally nicer to read. I know you may just be looking for something that 'Does the job' But it helps you when debugging and us when you're asking for help.
I'm going to give you a way that is marginally more secure than your one.
index.php
<form method="post" id="regform" action="register.php">
<input type="text" name="username" placeholder="Enter your email Address"required/>
<input type="password" name="password" placeholder="Enter your password" required/>
<input type="submit" class="indexbttn" id="indexbttn" name="enter"value="enter"/>
</form>
connect.php
<?php
$servername = "localhost";
$dbusername = "root";
$dbpassword = "root";
$dbname = "fyp";
try{
$pdo = new PDO("mysql:host=$servername;dbname=$dbname",$dbusername, $dbpassword);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
print "Error! Unable to connect: " . $e->getMessage() . "<br/>";
die();
}
?>
register.php
<?php
session_start();
require_once ('connect.php');
error_reporting(E_ALL);
ini_set('display_errors', 1);
if(isset($_POST['enter'])){
$username = !empty($_POST['username']) ? trim($_POST['username']) : null;
$pass = !empty($_POST['password']) ? trim($_POST['password']) : null;
$check (!filter_var($_POST['username'], FILTER_VALIDATE_EMAIL));
$cnt = "SELECT COUNT(username) AS num FROM users WHERE username = :username";
$stmt = $pdo->prepare($cnt);
$stmt->bindValue(':username', $username);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($row['num'] > 0){
die('That username already exists!');
}
$passHash = password_hash($pass, PASSWORD_BCRYPT, array("cost" => 12));
$insrt = "INSERT INTO users (username, password) VALUES (:username, :password)";
$stmt = $pdo->prepare($insrt);
$stmt->bindValue(':username', $username);
$stmt->bindValue(':password', $passHash);
$result = $stmt->execute();
if($result){
header( "refresh:5;url=index.php" );
echo 'You will be redirected in 5 seconds. If not, click here.';
}
}
?>
login.php
<?php
session_start();
require("connect.php");
if(isset($_POST['enter'])){
$username = !empty($_POST['username']) ? trim($_POST['username']) : null;
$pass = !empty($_POST['password']) ? trim($_POST['password']) : null;
$rtrv = "SELECT username, password, userid FROM users WHERE username = :username";
$stmt = $pdo->prepare($rtrv);
//Bind value.
$stmt->bindValue(':username', $username);
//Execute.
$stmt->execute();
//Fetch row.
$user = $stmt->fetch(PDO::FETCH_ASSOC);
//If $row is FALSE.
if($user === false){
//Could not find a user with that username!
die('Incorrect username');
}
else{
$validPassword = password_verify($pass, $user['password']);
if($validPassword){
$_SESSION['user_id'] = $user['username'];
$_SESSION['logged_in'] = time();
header( "Location: /protected.php" );
die();
} else{
die('Wrong password!');
}
}
}
?>
I have recently adapted some code from http://megarush.net/forgot-password-php/ to help me create a forgot password function. I have changed it to mysqli and added some bcrypt features when updating the password. In short form, the user types in their email address, get sent a link, and this link allows them to update their password but it also gets hashed again. My problem is... I can get the email to go to the user, but when the link is clicked it keeps saying "Invalid link or Password already changed" even when trying new email addresses. Any ideas where I've gone wrong? Appreciate the help guys!
I have a token table with email, token, and used.
forgot.php
<?php require 'header.php';
if (!isset($_GET['email'])) {
echo '<form action="forgot.php">
Enter Your Email Id:
<input type="text" name="email" />
<input type="submit" value="Reset My Password" />
</form>';
exit();
}
$email = $_GET['email'];
$sql = "SELECT email FROM user WHERE email='$email'";
$query = $mysqli_conn->query($sql);
if ($query->num_rows == 0) {
echo "Email id is not registered";
die();
}
$token = getRandomString(10);
$sql = "INSERT INTO `tokens` (`token`, `email`) VALUES ('{$token}','{$email}')";
$query = $mysqli_conn->query($sql);
function getRandomString($length) {
$validCharacters = "ABCDEFGHIJKLMNPQRSTUXYVWZ123456789";
$validCharNumber = strlen($validCharacters);
$result = "";
for ($i = 0; $i < $length; $i++) {
$index = mt_rand(0, $validCharNumber - 1);
$result.= $validCharacters[$index];
}
return $result;
}
function mailresetlink($to, $token) {
$subject = "Forgot Password";
$uri = 'http://' . $_SERVER['HTTP_HOST'];
$message = '
<html>
<head>
<title>Forgot Password</title>
</head>
<body>
<p>Click on the given link to reset your password Reset Password</p>
</body>
</html>
';
$headers = "MIME-Version: 1.0" . "\r\n";
$headers.= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers.= 'From: Admin<webmaster#example.com>' . "\r\n";
$headers.= 'Cc: Admin#example.com' . "\r\n";
if (mail($to, $subject, $message, $headers)) {
echo "We have sent the password reset link to your email id <b>" . $to . "
</b>";
}
}
if (isset($_GET['email'])) mailresetlink($email, $token);
?>
reset.php
<?php require 'header.php';
$token = $_GET['token'];
if (!isset($_POST['password'])) {
$sql = "SELECT email FROM tokens WHERE token='" . $token . "' and used=0";
$query = $mysqli_conn->query($sql);
while ($row = mysqli_fetch_array($query)) {
$email = $row['email'];
}
if ($email != '') {
$_SESSION['email'] = $email;
}
else die("Invalid link or Password already changed");
}
$password = $_POST['password'];
$email = $_SESSION['email'];
if (!isset($password)) {
echo '<form method="post">
enter your new password:<input type="password" name="password" />
<input type="submit" value="Change Password">
</form>';
}
if (isset($_POST['password']) && isset($_SESSION['email'])) {
$password = password_hash($password, PASSWORD_DEFAULT);
$sql = "UPDATE user SET password= '$password' where email='$email'";
$query = mysqli_query($sql);
if ($query) mysqli_query("UPDATE tokens SET used=1 WHERE token='$token'");
echo "Your password is changed successfully";
if (!$query) echo "An error occurred";
}
?>
UPDATE: The invalid error is now fixed and the form displays, but now it just appears saying 'an error occurred'. Added sql errors in to pick up any errors, it seems to be fine until it gets to updating the password as I have echoed variables and
if (isset($_POST['password']) && isset($_SESSION['email'])) {}
comes back working
The reason why your queries are not firing, is that you did not pass your db connection to all mysqli_query(), being in this block of code:
if (isset($_POST['password']) && isset($_SESSION['email'])) {
$password = password_hash($password, PASSWORD_DEFAULT);
$sql = "UPDATE user SET password= '$password' where email='$email'";
$query = mysqli_query($sql);
if ($query) mysqli_query("UPDATE tokens SET used=1 WHERE token='$token'");
echo "Your password is changed successfully";
if (!$query) echo "An error occurred";
}
Just as you did for $query = $mysqli_conn->query($sql);.
Remember to check for errors also.
This if (!$query) echo "An error occurred"; does not help you here.
Add error reporting to the top of your file(s) right after your opening PHP tag
for example
<?php error_reporting(E_ALL); ini_set('display_errors', 1); then the rest of your code, to see if it yields anything,
as well as or die(mysqli_error($mysqli_conn)) to mysqli_query().
Your present code is open to SQL injection. Use prepared statements, or PDO with prepared statements.
Footnotes:
You should use a conditional empty() rather than if ($email != ''), it's better.
Another thing: When using UPDATE, it's best to use mysqli_affected_rows() for truthness, as you could get a false positive.
http://php.net/manual/en/mysqli.affected-rows.php
Here is an example using mysqli_affected_rows() and I changed isset() to !empty() for the password POST array:
if (!empty($_POST['password']) && isset($_SESSION['email'])) {
$password = password_hash($password, PASSWORD_DEFAULT);
$sql = "UPDATE user SET password= '$password' where email='$email'";
$query = mysqli_query($mysqli_conn, $sql) or die(mysqli_error($mysqli_conn));
if (mysqli_affected_rows($mysqli_conn)){
mysqli_query($mysqli_conn, "UPDATE tokens SET used=1 WHERE token='$token'");
echo "Your password is changed successfully";
}
else {
echo "An error occured: " . mysqli_error($mysqli_conn);
}
}
Edit:
Change this whole block:
$token = $_GET['token'];
if (!isset($_POST['password'])) {
$sql = "SELECT email FROM tokens WHERE token='" . $token . "' and used=0";
$query = $mysqli_conn->query($sql);
while ($row = mysqli_fetch_array($query)) {
$email = $row['email'];
}
if ($email != '') {
$_SESSION['email'] = $email;
}
else die("Invalid link or Password already changed");
}
while getting rid of this code block (for now):
if ($email != '') {
$_SESSION['email'] = $email;
}
else die("Invalid link or Password already changed");
The first code block above to be replaced with and checking if the row exists with mysqli_num_rows():
if (isset($_GET['token'])) {
$token = $_GET['token'];
$sql = "SELECT email FROM tokens WHERE token='" . $token . "' and used=0";
$query = $mysqli_conn->query($sql) or die(mysqli_error($mysqli_conn));
if(mysqli_num_rows($query) > 0){
while ($row = mysqli_fetch_array($query)) {
$email = $row['email'];
$_SESSION['email'] = $email;
}
}
}
I am having trouble the code executes correctly but when I submit with nothing in fields I get that you did not fill out all required fields message but when I submit with text in then I get the same message I do not know why
Also I am having stmt problems, I am trying to do a clean login script with stmt
login.inc.php
<?php
$ud = '';
$error = '';
$email = '';
$password = '';
if (isset($_POST['login'])) {
$email = $_POST['email'];
$password = $_POST['password'];
$email = mysql_real_escape_string($email);
$password = mysql_real_escape_string($password);
if (empty($email) || empty($password)) {
$error = 'You did not fill out all the required field\'s.';
} else {
$stmt = $conn->prepare("SELECT id, username, password, email FROM users WHERE email = ?");
$stmt->bind_param('s', $email);
if (!$stmt->execute()) {
$error = 'No account has the email: ' . $email . '.';
} else {
$ud = $stmt->get_result();
$stmt->bind_result($db_id_login, $db_username_login, $db_password_login, $db_email_login);
$stmt->store_result();
$password = md5($password);
if ($password == $db_password_login) {
// start users session
} else {
$error = 'The password is incorrect.';
}
}
$stmt->close();
}
}
?>
I have look at your code, and the main issue was your if statement logic in general and your prepared statement order and the way you have written you code. Here is a complete working solution.
I have changed password to plain text just for testing, but you should use better hashing then md5.
No reason to make your $username and $password empty at the top of the code.
I suggest you to use required="required" in input fields and make your email validation in your input field.
The login form can be done in many ways, I have just solved in regards to your code, but I suggest you to look at: http://www.wikihow.com/Create-a-Secure-Login-Script-in-PHP-and-MySQL for inspiration.
I have put my notes inside the code for your orientation.
<?php
// db connection
$dbcon_servername = "localhost";
$dbcon_username = "root";
$dbcon_password = "";
$dbcon_database = "dummy";
$conn = new mysqli($dbcon_servername, $dbcon_username, $dbcon_password, $dbcon_database);
if ($conn->connect_error)
die("Connection failed: " . $conn->connect_error);
// login logic
$error = "";
if (isset($_POST['login']))
{
// you can put the input var directly inside mysql real escape
$email = mysql_real_escape_string($_POST['email']);
$password = mysql_real_escape_string($_POST['password']);
if (empty($email) || empty($password))
{
$error = "You did not fill out all the required field\'s.";
} else
{
//sql statement for its own, cleaner and easier for debugging
$sql = "SELECT `id`,`username`,`password` FROM `users` WHERE `email` = ?";
if ($stmt = $conn->prepare($sql))
{
$stmt->bind_param('s', $email);
$stmt->execute();
$stmt->store_result();
//check if you get at least one results you have to ensure you
//do not have double email as account, one way to that
//making email as key in your database and make email check
//mechanism to check for double when registering users.
if ($stmt->num_rows == 1)
{
$stmt->bind_result($db_id, $db_username, $db_password);
$stmt->fetch();
if ($password == $db_password)
{
// successful login
echo "The email address: $email with username $db_username exist in the database" . "<br />";
echo "id=$db_id, username=$db_username, password=$db_password \n";
} else
{
$error = "The password is incorrect";
}
} else
{
$error = "No account has the email: $email";
}
}
$stmt->close();
}
}
$conn->close();
?>
<html>
<head><title>Login form</title>
<head>
<body>
<h3>Login form</h3>
Click here to main page or some thing else</br>
<form action="form.php" method="post">
Enter Email: <input type="text" name="email"/></br>
Enter Password: <input type="password" name="password"/></br>
<input type="submit" name="login" value="Register"/>
<?php echo $error ?>
</form>
</body>
</html>
Help please with this password change script
here's mys html code
<form method="POST" action="pass.php">
Current Password:
<input type="password" name='password'/>
New Password
<input type="password" id="password1" name="password1"/>
Retype New Password:</td>
<input type="password" id="password2" name="password2"/>
<input type="submit" value="Change Password">
</form>
here's my php script for change password. it's working fine but when i try to login the new password it is always incorrect.
$userData = $qry->fetch(PDO::FETCH_ASSOC);
$hash = hash('sha256',$userData['salt'].hash('sha256',$password));
if ($hash == $userData['password']) {
$hash1 = hash('sha256', $password1);
function createSalt()
{
$text = md5(uniqid(rand(), TRUE));
RETURN substr($text, 0, 3);
}
$salt = createSalt();
$pass = hash('sha256', $salt . $hash1);
$qry = $handler->prepare( "UPDATE login SET password = ? WHERE id = ?" );
$qry->execute(array($pass,$id));
$error = 'Password successfully changed! The system will now log you out. Please login again.';
session_destroy();
header('refresh:5; url=/../lab/login.php');
}else{
$error = 'Incorrect Password.';
}
Here's my login script for reference.
<?php
$errors = array();
if ($email&&$pass){
$qry = $handler->prepare( "SELECT `email` FROM login WHERE `email` = ?" );
$qry->bindValue( 1, $email );
$qry->execute();
$row = $qry->rowCount();
if ($row == 1){
$qry = $handler->prepare( "SELECT * FROM login WHERE email = ? AND stat = '1'" );
$qry->bindValue( 1, $email );
$qry->execute();
$row = $qry->rowCount();
if ($row == '1'){
$userData = $qry->fetch(PDO::FETCH_ASSOC);
$hash = hash('sha256',$userData['salt'].hash('sha256',$pass));
if($hash == $userData['password']){
$_SESSION['email']=$email;
header('Location:/../lab/profile.php');
}
else{
$errors = "<center>The Password/Email you Entered is incorrect. Please check your login Details and <br><a href='/../lab/login.php' style='font-size:12px;text-decoration:underline;'>Login Again</a></center> ";
}
}
else{
$errors = "Your Account is not yet activated. Please check your email.";
}
}
else{
$errors = "<center>The Password/Email you Entered is incorrect. Please check your login Details and <br><a href='/../lab/login.php' style='font-size:12px;text-decoration:underline;'>Login Again</a></center>";
}
}
else{
$errors = "Please fill in the Email and Password fields to login";
}
?>
Everything is working. It's just when I try to change password and then login the new password, the system returns incorrect password. maybe there's some problem with encrypting the new password.
Thanks
Is that the full php script?
There are many ways to debug this.
Try to echo $_POST['password1']; maybe it doesn't have a value.
did you try $hash1 = hash('sha256', $_POST['password1']);?
or maybe you forgot to hash the $pass in if ($email&&$pass)
From what I saw on your code. Listed above is the most critical reason of your problem.
Hi im having a problem with my change password script. im trying to allow a user to change their password in the mysql table 'ptb_users.password' it's suppose to store this as md5.
When i hit submit in my form, i'm assuming it goes to changepassword.php but the page is just blank, nothing is echoed and im not getting any errors.
Can someone please show me where im going wrong with this, thanks
Here's my form:
<?php
// CONNECT TO THE DATABASE
require('includes/_config/connection.php');
// LOAD FUNCTIONS
require('includes/functions.php');
// GET IP ADDRESS
$ip_address = $_SERVER['REMOTE_ADDR'];
?>
<?php require_once("includes/sessionframe.php");
require('includes/checks.php');
?>
<?php
if (isset ($_GET['to'])) {
$user_to_id = $_GET['to'];
}
?>
<?php
//We check if the form has been sent
if(isset($_POST['subject'], $_POST['message_content']))
{
$subject = $_POST['subject'];
$content = $_POST['message_content'];
//We remove slashes depending on the configuration
if(get_magic_quotes_gpc())
{
$subject = stripslashes($subject);
$content = stripslashes($content);
}
//We check if all the fields are filled
if($_POST['subject']!='' and $_POST['message_content']!='')
{
$sql = "INSERT INTO ptb_messages (id, from_user_id, to_user_id, subject, content) VALUES (NULL, '".$_SESSION['user_id']."', '".$user_to_id."', '".$subject."', '".$content."');";
mysql_query($sql, $connection);
echo "<div class=\"infobox2\">The message has successfully been sent.</div>";
}
}
if(!isset($_POST['subject'], $_POST['message_content']))
if (empty($_POST['subject'])){
$errors[] = 'The subject cannot be empty.';
if (empty($_POST['body'])){
$errors[] = 'The body cannot be empty.';
}
}
{
?>
<form method="post" action="includes/changepassword.php" name="form1" id="form1">
<input type="password" name="oldpassword" id="password" class="subject" placeholder="Old Password">
<input type="password" name="oldpassword" id="password" class="message" placeholder="Old Password">
<input type="password" name="newpassword" id="newpassword" class="message" placeholder="New Password">
<input type="image" src="assets/img/icons/loginarrow1.png" name="submit" id="submit" class="submit">
</form>
And here's my mysql function:
<?php
require_once("session.php");
require_once("functions.php");
require('_config/connection.php');
?>
<?php
session_start();
include '_config/connection.php';
$password = $_POST['password'];
$newpassword = $_POST['newpassword'];
$confirmnewpassword = $_POST['confirmnewpassword'];
$result = mysql_query("SELECT password FROM ptb_users WHERE id=".$_SESSION['user_id']."");
if(!$result)
{
echo "The username you entered does not exist";
}
else
if($password!= mysql_result($result, 0))
{
echo "";
}
if($newpassword=$confirmnewpassword)
{
$newpassword=md5($newpassword);
$sql=mysql_query("UPDATE ptb_users SET password='$newpassword' WHERE id=".$_SESSION['user_id']."");
}
if($sql)
{
echo "Thank You. Your Password has been successfully changed.";
}
else
{
echo "The new password and confirm new password fields must be the same";
}
?>
if(isset($_POST['submit']))
{
$email = $_POST['email'];
echo $newpassword = ($_POST['password1']);
echo $confirmpasssword = ($_POST['password2']);
if($newpassword=$confirmpassword)
{
echo $newpassword = md5($newpassword);
echo $result = mysql_query("UPDATE users SET password='$newpassword' WHERE email='$email' ");
}
if($result)
{
echo "Thank You. Your Password has been successfully changed.";
}
else
{
echo "The new password and confirm password fields must be the same";
}
}
can anyone tell me is this correct coding, to change password and store in mysqldb.
first you do not check the old password properly (md5 stored, plaintext compare... won't work)
second you do not have any confirmpassword set, so this wont work too
what would work is:
$password = md5($_POST['password']);
$newpassword = md5($_POST['newpassword']);
$result = mysql_query("SELECT password FROM ptb_users WHERE id=".$_SESSION['user_id']." AND password = '".$password."'");
if(!$result)
{
echo "The username you entered does not exist or old password didn't match";
}
else
{
$sql=mysql_query("UPDATE ptb_users SET password='$newpassword' WHERE id=".$_SESSION['user_id']."");
}
if($sql)
{
echo "Thank You. Your Password has been successfully changed.";
}
There are many things wrong with this.
Let's get the basics out of the way first:
Don't use mysql_ functions. switch to PDO or mysqli while you can.
md5 is in its dying days. See this answer - understandably, you may be so entrenched in md5 you can't get out without pestering every user to update their pw.
Your problem then is this:
if($password!= mysql_result($result, 0))
You're not comparing against a md5 stored hash. It should be something like this:
if(md5($password) != mysql_result($result, 0))
and this:
if($newpassword=$confirmnewpassword)
is just reassigning a variable. I think you wanted
if($newpassword == $confirmnewpassword)
As for output, you may want to consider the if/else structures you're using here. This could be cleaned up significantly and all together looks out of date. Maybe just an opinion.
If you have a specific thing to hone in on, let me know and I may update.
EDIT
This whole block should be cleaned. Something like this may help:
if(!$result)
{
echo "The username you entered does not exist";
}
else
{
if(md5($password) != mysql_result($result, 0))
{
echo "Current PW does not match what we have";
}
else
{
if($newpassword == $confirmnewpassword)
{
$newpassword=md5($newpassword);
$sql=mysql_query("UPDATE ptb_users SET password='$newpassword' WHERE id=".$_SESSION['user_id']."") or die(mysql_error());
if($sql)
{
echo "Thank You. Your Password has been successfully changed.";
}
}
else
{
echo "The new password and confirm new password fields must be the same";
}
}
}