php check and validate form input with mysql database [duplicate] - php

This question already has an answer here:
PHP's white screen of death [duplicate]
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 3 years ago.
Basically I have this form that asks for email and password.
What I want to do is to compare and check if the inputs match with the data from my table/database.
This is my registration.php (the form)
<form action="Authentication.php" method="post">
<b>Returning Intern Login</b><br/><br/>
Enter your e-mail address: <input type="text" name="email" /><br/><br/>
Enter your password: <input type="password" name="pw2"/><br/><i>(Passwords are case-sensitive and must be 6 characters long)</i><br/><br/>
<input type="reset" value="Reset Login Form" />
<input type="submit" name="submit2" value="Log In" /><hr/><br/>
</form>
and this is the Authentication.php
session_start();
$link = mysqli_connect('localhost','root','');
$database = mysqli_select_db($link,'internship');
$user = $_POST['email'];
$pass = $_POST['pw2'];
// User is logging in
if (isset($_POST["submit2"]))
{
if (empty ($user)) //if username field is empty echo below statement
{
echo "<font color='red'>***You must enter your unique username (email).***</font><br/><br/>";
}
if (empty ($pass)) //if password field is empty echo below statement
{
echo "<font color='red'>***You must enter your unique password.***</font><br/><br/>";
}
}
else
{
$query = "SELECT * FROM Interns WHERE email = '". mysqli_real_escape_string($link,$user) ."' AND password = '". mysqli_real_escape_string($link,$pass) ."'" ;
$result = mysqli_query($link,$query);
if (mysqli_num_rows($result) == 1)
{
echo "pass"; //Pass, do something
}
else
{
echo "fail"; //Fail
}
}
session_write_close();
It works with the empty inputs.
But when I gave an email and password exactly same from the database/table,
It displays white blank page..

You need to write the entire code within an if statement to ensure the field is filled in, like so:
if (isset($_POST["submit2"]))
{
if (empty ($user)) //if username field is empty echo below statement
{
/* Code */
}
if (empty ($pass)) //if password field is empty echo below statement
{
/* Code */
}
$query = "SELECT * FROM Interns WHERE email = '". mysqli_real_escape_string($link,$user) ."' AND password = '". mysqli_real_escape_string($link,$pass) ."'" ;
$result = mysqli_query($link,$query);
if (mysqli_num_rows($result) == 1)
{
echo "pass"; //Pass, do something
}
else
{
echo "fail"; //Fail
}
}
else
{
echo "Empty input submit2"; // empty $_POST["submit2"]
}
Hope this helps.

Mysqli takes 4 parameters hostname,username,password, and dbname:
<?php
session_start();
$link = mysqli_connect('localhost','root','','internship');
// User is logging in
if (isset($_POST["submit2"]))
{
$user = $_POST['email'];
$pass = $_POST['pw2'];
if (empty($user)) //if username field is empty echo below statement
{
echo "<font color='red'>***You must enter your unique username (email).***</font><br/><br/>";
}
else if (empty ($pass)) //if password field is empty echo below statement
{
echo "<font color='red'>***You must enter your unique password.***</font><br/><br/>";
}
else
{
$query = "SELECT * FROM Interns WHERE email = '". $user ."' AND password = '".$pass."'" ;
$result = mysqli_query($link,$query);
if (mysqli_num_rows($result) == 1)
{
echo "pass"; //Pass, do something
}
else
{
echo "fail"; //Fail
}
}
session_write_close();
?>

Related

SQL insert in php not working

Im very new to php and trying to get a register up and working , my code at the minute is only loading the username into the database and nothing else. Although it does enter values into other fields of the database if I hard-code them into sql insert and dont use
$users_Password
etc. btw I know this is terrible code and passwords should be hashed etc but ive literally just tore this code apart because this wont work and will add everything back in after this is sorted out cheers , this is my code
form
<form id = "Register_form" action="Register.php" method="post">
Username: <input type="text" name="Username"><br>
Password: <input type="password" name="Password"><br>
Confirm Password: <input type="password" name="ConfirmPassword"><br>
First Name: <input type="text" name="FirstName"><br>
Surname: <input type="text" name="Surname"><br>
Address Line 1: <input type="text" name="AddressLine1"><br>
Address Line 2: <input type="text" name="AddressLine2"><br>
City: <input type="text" name="City"><br>
Telephone: <input type="text" name="Telephone"><br>
Mobile: <input type="text" name="Mobile"><br></br>
<input type="submit">
then in the Register.php file
<?php
// create connection
$con=mysqli_connect("localhost","root","","book");
// check connection
if(mysqli_connect_errno($con)){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$users_Username = $_POST['Username'];
$users_Password = $_POST['Password'];
$users_ConfirmPassword = $_POST['ConfirmPassword'];
$users_FirstName = $_POST['FirstName'];
$users_Surname = $_POST['Surname'];
$users_AddressLine1 = $_POST['AddressLine1'];
$users_AddressLine2 = $_POST['AddressLine2'];
$users_City = $_POST['City'];
$users_Telephone = $_POST['Telephone'];
$users_Mobile = $_POST['Mobile'];
//Multiple Error checkings such as
if ($users_Username == "")
{
echo "Please enter a username";
echo "<script>setTimeout(\"location.href = 'http://localhost/webD/Assignment/Register_Form.php';\",1500);</script>";
}
else if ($users_Password = "")
{
echo "Please enter a password";
echo "<script>setTimeout(\"location.href = 'http://localhost/webD/Assignment/Register_Form.php';\",1500);</script>";
}
else if ($users_ConfirmPassword == $users_Password)
{
if (strlen($users_Password)<=6)
{
$sql = "INSERT INTO users VALUES ('$users_Username', '$users_Password', '$users_FirstName', '$users_Surname','$users_AddressLine1','$users_AddressLine2','$users_City','$users_Telephone','$users_Mobile')";
if($con->query($sql) === TRUE)
{
echo "User succesfully registered";
echo "<script>setTimeout(\"location.href = 'http://localhost/webD/Assignment/Log_In_Screen.php';\",1500);</script>";
}
else
{
echo "Unable to register user, Please try again";
echo "<script>setTimeout(\"location.href = 'http://localhost/webD/Assignment/Register_Form.php';\",1500);</script>";
}
//echo "<pre>\n$sql\n</pre>\n";
mysql_query($sql);
}
else
{
echo "The password you entered is too long, max characters is 6";
echo "<script>setTimeout(\"location.href = 'http://localhost/webD/Assignment/Register_Form.php';\",1500);</script>";
}
}
else
{
echo "Passwords do not match, Please try again";
echo "<script>setTimeout(\"location.href = 'http://localhost/webD/Assignment/Register_Form.php';\",1500);</script>";
}
mysqli_close($con);
?>
It seems like nothing will insert into the database except the username , any one have a way to fix this ?
Cheers
You had stuff all over the place and were mixing mysql and mysqli not to mention you left yourself wide open for SQL injection. Using the script you had I stuck with mysqli used prepared statements and split your validation and persistence up. There are comments that will explain some of this
<?php
$users_Username = $_POST['Username'];
$users_Password = $_POST['Password'];
$users_ConfirmPassword = $_POST['ConfirmPassword'];
$users_FirstName = $_POST['FirstName'];
$users_Surname = $_POST['Surname'];
$users_AddressLine1 = $_POST['AddressLine1'];
$users_AddressLine2 = $_POST['AddressLine2'];
$users_City = $_POST['City'];
$users_Telephone = $_POST['Telephone'];
$users_Mobile = $_POST['Mobile'];
//LETS JUST DO ERROR CHECKING ONLY
$valid = true; //Used to verify that user input is as expected.
//All the validation as before just as ifs and will set the
//$valid flag to false when validation fails.
if ($users_Username == "")
{
$valid = false;
echo "Please enter a username";
echo "<script>setTimeout(\"location.href = 'http://localhost/webD/Assignment/Register_Form.php';\",1500);</script>";
}
if ($users_Password = "")
{
$valid = false;
echo "Please enter a password";
echo "<script>setTimeout(\"location.href = 'http://localhost/webD/Assignment/Register_Form.php';\",1500);</script>";
}
if (strlen($users_Password)>6)
{
$valid = false;
echo "The password you entered is too long, max characters is 6";
echo "<script>setTimeout(\"location.href = 'http://localhost/webD/Assignment/Register_Form.php';\",1500);</script>";
}
if ($users_ConfirmPassword != $users_Password)
{
$valid = false;
echo "Passwords do not match, Please try again";
echo "<script>setTimeout(\"location.href = 'http://localhost/webD/Assignment/Register_Form.php';\",1500);</script>";
}
//Separating validation and persistence mean you only
//open a connection and persist when needed.
if($valid)
{
//NOW WE ONLY CONNECT WHEN YOU NEED TO!
$con=mysqli_connect("localhost","root","","book");
// check connection
if(!$con)
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//YOU MAY NEED TO SPECIFY THE COLUMNS YOU ENTER
$stmt = mysqli_prepare($con, "INSERT INTO users VALUES (?,?,?,?,?,?,?,?,?)");
//ASSUMING ALL 9 PARAMETERS ARE STRINGS hence the sssssssss
mysqli_stmt_bind_param($stmt, 'sssssssss', $users_Username,$users_Password,$users_FirstName,$users_Surname,$users_AddressLine1,$users_AddressLine2,$users_City,$users_Telephone,$users_Mobile);
if(mysqli_stmt_execute($stmt))
{
echo "User succesfully registered";
echo "<script>setTimeout(\"location.href = 'http://localhost/webD/Assignment/Log_In_Screen.php';\",1500);</script>";
}
mysqli_close($con);
}
?>
What content lands in your database?
Try the following in the appropriate line:
"INSERT INTO users VALUES ('".$users_Username."', '".$users_Password."', '".$users_FirstName."', '".$users_Surname."','".$users_AddressLine1."','".$users_AddressLine2."','".$users_City."','".$users_Telephone."','".$users_Mobile."')";
PHP Params cant be evaluated in ' ' so you have to use string concatenation.

PHP form only submits data for one row

I am working on a simple registration system and after hours of research am still stuck.
If my database is clear (I delete any rows in the table), and I submit the form, it sends a validation email and activates and allows me to login.
If I try to create another account with the same email, I am not getting my error message like I should be, telling the user "the email has already been registered." It just takes me to a blank page, even if I use a new email address after the first row has been created.
When I look at my table, the row created by the form (the first time) has the auto-inc ID which is right, the username is input into the row, but password, email, and activation all say '0'.
Can anyone see where the error is in my code? I need the code to verify that the email entered isn't already used, and if it is, to display the errormessage. If it isn't, it should be creating a new row in the table with the information.
I know I need to hash the password. I'm just trying to get the information in the table right before I proceed with security.
index.php
<?php
include 'sessions.php';
if(isset($_SESSION['errormessage'])){
echo ($_SESSION['errormessage']);
unset ($_SESSION['errormessage']);
}
?>
<html>
<head>
<title>Registration Form</title>
</head>
<body>
<form name="newForm" method="post" action="createaccount.php">UserName:
<input type="text" name="newUserName" size="15" maxlength="15">
<br>Password:
<input type="password" name="newPass1" size="15">
<br>Confirm Password:
<input type="password" name="newPass2" size="15">
<br>Email:
<input type="email" name="newEmail" size="15">
<br>
<input type="submit" name="newSubmit">
<input type="reset" name="newReset">
</p>
</form>
<hr>
<form name="newForm" method="post" action="login.php">
<strong>Already Registered? Login Here:</strong>
<br>
UserName:
<input type="text" name="UserName" size="15" maxlength="15">
<br>Password:
<input type="password" name="Pass1" size="15">
<br>
<input type=submit name=SubmitButton value=Submit>
<input type=reset name=ResetButton value=Clear>
</form>
</body>
</html>
createaccount.php
<?php
include ('sessions.php');
include ('database_connection.php');
//function to test password
function passwordStrength($pwd) {
//test for at least 8 characters
if (strlen($pwd) < 8) {
return false;
}
//test for max length
if (strlen($pwd) > 16) {
return false;
}
//test to see if password contains number
if(!preg_match("#[0-9]+#", $pwd)) {
return false;
}
//test to see if password has capital letter
if(!preg_match("#[A-Z]+#", $pwd)) {
return false;
}
//test to see if password has a lowercase letter
if(!preg_match("#[a-z]+#", $pwd)) {
return false;
}
//test to see if password has special character
if(!preg_match("#[^0-9A-Za-z]#", $pwd)) {
return false;
}
//test to see if password contains a space
if (strpos($pwd, ' ') > 0) {
return false;
}
else {
return true;
}
return true;
}
if(isset($_POST['newSubmit'])){
if(empty($_POST['newUserName'])) {
$_SESSION['errormessage'] = "Please enter a username!";
header("Location: index.php");
}
else if (strlen($_POST['newUserName']) < 4) {
$_SESSION['errormessage'] = "Username is too short!";
header("Location: index.php");
} else if(strlen($_POST['newUserName']) > 16) {
$_SESSION['errormessage'] = "Username is too long!";
header("Location: index.php");
} else if(empty($_POST['newPass1'])) {
$_SESSION['errormessage'] = "You must enter a password!";
header("Location: index.php");
} else if(empty($_POST['newPass2'])) {
$_SESSION['errormessage'] = "You must confirm your password!";
header("Location: index.php");
} else if($_POST['newPass1'] !== $_POST['newPass2']) {
$_SESSION['errormessage'] = "Passwords do not match!";
header("Location: index.php");
} else if(!passwordStrength($_POST['newPass1'])) {
$_SESSION['errormessage'] = "Password does not meet requirements!";
header("Location: index.php");
} else if(empty($_POST['newEmail'])) {
$_SESSION['errormessage'] = "Must enter an email address!";
header("Location: index.php");
} else {
$Email = $_POST['newEmail'];
$name = $_POST['newUserName'];
$Password = $_POST['newPass1'];
//echo "All fields accepted!";
//$pwd = $_POST['newPass1'];
//echo hash("sha256", $pwd);
// Make sure the email address is available:
$query_verify_email = "SELECT * FROM userDB WHERE email ='$Email'";
$result_verify_email = mysqli_query($db, $query_verify_email);
if (!$result_verify_email) {//if the Query Failed ,similar to if($result_verify_email==false)
$_SESSION['errormessage'] = "Sorry, that email address has already been registered!<br />If you already have an account, login below.<br /><br />";
header("Location: index.php");
}
if (mysqli_num_rows($result_verify_email) == 0) { // IF no previous user is using this email .
// Create a unique activation code:
$activation = md5(uniqid(rand(), true));
$query_insert_user = "INSERT INTO `userDB` ( `username`, `email`, `password`, `activation`) VALUES ( '$name', '$Email', '$Password', '$activation')";
$result_insert_user = mysqli_query($db, $query_insert_user);
if (!$result_insert_user) {
echo 'Query Failed ';
}
if (mysqli_affected_rows($db) == 1) { //If the Insert Query was successfull.
//send the email
$to = $_POST['newEmail']; // this is your Email address
$from = "mtshort87#gmail.com"; // this is the sender's Email address
$subject = "Account Succesfully Created";
$message = "Thank you for creating an account. Please activate it now using the link below!";
$message2 = "http://cts.gruv.org/short/form/activate.php?username=".$_POST['newUserName']."\n";
$headers = "From:" . $from;
$headers2 = "From:" . $to;
mail($to,$subject,$message2,$message,$headers);
mail($from,$subject,$message2,$message,$headers); // sends a copy of the message to the sender
$_SESSION['errormessage'] = "A confirmation e-mail has been sent to you. Please activate your account to login.";
header("Location: index.php");
}
mysqli_close($db);//Close the DB Connection
}
}
}
activate.php
<?php
include 'sessions.php';
include 'database_connection.php';
if (isset($_GET['Email']) && preg_match('/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*#([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/', $_GET['Email']))
{
$email = $_GET['Email'];
}
if (isset($_GET['key']) && (strlen($_GET['key']) == 32))//The Activation key will always be 32 since it is MD5 Hash
{
$key = $_GET['key'];
}
if (isset($Email) && isset($key))
{
// Update the database to set the "activation" field to null
$query_activate_account = "UPDATE userDB SET activation=NULL WHERE(email ='$Email' AND activation='$key')LIMIT 1";
$result_activate_account = mysqli_query($db, $query_activate_account) ;
// Print a customized message:
if (mysqli_affected_rows($db) == 1)//if update query was successfull
{
echo '<div class="success">Your account is now active. You may now Log in</div>';
} else
{
echo '<div class="errormsgbox">Oops !Your account could not be activated. Please recheck the link or contact the system administrator.</div>';
}
mysqli_close($db);
} else {
echo '<div class="errormsgbox">Error Occured .</div>';
}
?>
If any more information is requested I will edit this post.
$query_verify_email = "SELECT * FROM userDB WHERE email ='$Email'";
$result_verify_email = mysqli_query($db, $query_verify_email);
if (!$result_verify_email) {//if the Query Failed ,similar to if($result_verify_email==false)
$_SESSION['errormessage'] = "Sorry, that email address has already been registered!<br />If you already have an account, login below.<br /><br />";
header("Location: index.php");
}
http://php.net/manual/en/mysqli.query.php
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or
EXPLAIN queries mysqli_query() will return a mysqli_result object. For
other successful queries mysqli_query() will return TRUE.
Since you are using a correct SQL select statement, mysqli_query will return a mysqli_result object.
There is a num_rows attribute in mysqli_result that indicates the number of rows found. You can use it to check if there is a record with that email.
Always use LIMIT 1 when you expect 1 result.
FIX:
$query_verify_email = "SELECT * FROM userDB WHERE email ='$Email' LIMIT 1";
$result_verify_email = mysqli_query($mysqli, $query_verify_email);
if (is_object($result_verify_email) && $result_verify_email->num_rows > 0) {
echo "Email already exists";
}

Checking if username exists POSTBACK

I want to check using the POSTBACK method i the user exists in mysql table. I studying mysql and i understand it will be removed soon but I cant change at the moment. I want the alert to pop up next to the username text box if it already exists.At the moment it isnt working. I have a similar code for password and password confirmation but i think this differs since i need a query. This is what i have:
<?php
$passErr = $pass1Err = "";
$passw = $passw1 = "";
$userErr="";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["password"])) {
$passErr = "Password is required";
}
if (empty($_POST["passconfirm"])) {
$pass1Err = "Password confirmation is required";
}
if ($_POST['password']!= $_POST['passconfirm'])
{
$passErr = "Passwords must be the same";
$pass1Err = "Passwords must be the same";
}
}
else {
if (isset($_REQUEST["submit"]))
{
if (isset($_POST["submit"]))
{
$firstname = mysql_real_escape_string($_POST["gname"]);
$middlename = mysql_real_escape_string($_POST["mname"]);
$lastname = mysql_real_escape_string($_POST["surname"]);
$user = mysql_real_escape_string($_POST["username"]);
$addy = mysql_real_escape_string($_POST["address"]);
$post = mysql_real_escape_string($_POST["postcode"]);
$sta = mysql_real_escape_string($_POST["state"]);
$telephone = mysql_real_escape_string($_POST["tel"]);
$pass = mysql_real_escape_string($_POST["password"]);
$systemuser= mysql_real_escape_string($_POST["susername"]);
$sql2 = "SELECT username FROM users WHERE username= '$user'";
$rs = mysql_query($sql2, $conn)
or die ('Problem with query' . mysql_error());
$num_rows = mysql_num_rows($rs);
if(isset($_POST['username'])) {
if($num_rows != 0){
$userErr = "Username already exists";
}
}
}
}
mysql_close($conn);
}
?>
this is what i got in the form:
<label>Chosen Username:</label> <input type="text" name="username" value="<?php
echo $userErr;?>"/><span class="error">* <?php echo $userErr;?></span><br />
<label>Password:</label> <input type="password" name="password" value="<?php
echo $passw;?>"/><span class="error">* <?php echo $passErr;?></span><br />
<br />
<label>Password confirmation:</label> <input type="password" name="passconfirm" value="<?php
echo $passw1;?>"/><span class="error">* <?php echo $pass1Err;?></span><br />
To acheive what your looking for, instead of using
$num_rows = mysql_num_rows($rs);
if(isset($_POST['username'])) {
if($num_rows != 0){
$userErr = "Username already exists";
}
}
replace it with
$num_rows = mysql_num_rows($rs);
if(isset($_POST['username'])) {
$userErr = "Username field cannot be empty";
}elseif($num_rows > 0){
$userErr = "Username already exists";
}
That way if the Username field is empty, it will error out. And this will also achieve your goal of checking the database to see if the user exists or not.
You need to know if request with username return something so error messsage else do insert new user,
$sql2 = "SELECT * FROM users WHERE username= '$user'";
$rs = mysql_query($sql2, $conn) or die ('Problem with query' . mysql_error());
if($num_rows=mysql_fetch_array($rs)){
$userErr = "Username already exists";
// ....
} else{
// $SQL = "INSERT INTO users SET ...
}

PHP Login Script - The password is incorrect but the user exists?

My username & password is correct but when i run this script and when i test my login i keep getting = "The password is incorrect but the user exists". Can anyone help?
Here is my Script;
<?php
include ("db.php");
if (isset($_SESSION['loggedin']) == "1") {
echo "You are already logged in. Go home";
} else {
if (isset($_POST['login'])) {
$username = strip_tags(mysql_real_escape_string($_POST['username']));
$password = md5(strip_tags(mysql_real_escape_string($_POST['password'])));
if (empty($username) || empty($password)) {
echo "Enter both fields.";
} else {
$userQ = mysql_query("SELECT * FROM users WHERE `username` = '{$username}'");
if (mysql_num_rows($userQ) == 0) {
echo "This user does not exist.";
} else {
$userA = mysql_fetch_array($userQ);
if ($password !== $userA["password"]) {
echo "The password is incorrect but the user exists.";
} else {
$_SESSION['loggedin'] = "1";
header("Location: index.php");
exit;
}
}
}
}
?>
<form method="post">
Username: <input type="text" name="username" maxlength="25" /><br />
Password: <input type="password" name="password" maxlength="20" /><br />
<input type="submit" name="login" value="Login" />
</form>
<?php
}
?>
Any Help would be great, i have just started to learn php and not sure if this code is correct.
$userA = mysql_fetch_array( $userQ ); this will return array. You need to iterate it and return associative array to check each record like;
.....
while ($row = mysql_fetch_assoc( $userQ)) {
$userA = $row["password"];
}
if ( $password !== $userA["password"] ) {
echo "The password is incorrect but the user exists.";
}
.....
There is iteration in above code, but it will always have one result, because username is unique(I think)
I think you may have multiple users with the same username. Check your database for this. If not, then try to remove mysql_real_escape_string() before using md5 on it.
On a side note, if you are starting to leran PHP then don't use mysql functions anymore. Try to use mysqli or PDO extensions. Mysql functions are deprecated as of PHP 5.5.

change password in mysql table?

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";
}
}
}

Categories