PHP - Php Md5 Password Encryption And Db Entry Problem - 03.19.12
Hello Everyone,
I have built a simple registration form shown below and Iam trying to get the users to have their passwords encrypted and then entered into my database. I am attempting to use md5 encryption. I have also attached the database connection script. My goal is when I check my database, I want to see the following: ( id, name, username, encrypted password ) The issue I have is that the form does not process completely. All I get this error (Error: Unknown column 'd8578edf8458ce06fbc5bb76a58c5ca4' in 'field list' ). Could some tell me or show me " What is it that needs to be corrected either in my Code or SQL insert and /or my Variables" to make this work correctly. I know that its probably a very, very simple fix... Im just stuck at this point. I really appreciate your help. thanks, mrjap1 Code: [Select] <?php error_reporting(0); if($_POST['submit']) { //Begining of full IF Statment $name = $_POST['name']; $username = $_POST['username']; $password = $_POST['password']; $confirm_password = $_POST['confirm_password']; // Encrypt Pasword $enc_password = md5($password); //$enc_password2 = md5($confirm_password); // Confirm All feild were filled out when submit button was pressed if($name && $username && $password && $confirm_password) { // Confirm that the NAME that you used is NOT greater than 30 characters if(strlen($name)>24) { echo "<h2><center>YOUR NAME IS TOO LONG!!!!</center></h2><br>"; } // Confirm that the USERNAME that you used is NOT greater than 10 characters if(strlen($username)>10) { echo "<h2><center>YOUR USERNAME IS TOO LONG!!!!</center></h2><br>"; } else { // Confirm that the PASSWORD that you used MATCH & Between 6 and 15 characters if(strlen($password)>10 || strlen($password)<6) { echo "<h2><center>YOUR PASSWORD MUST BE BETWEEN 6 and 15 CHARACTERS!!!!</center></h2><br>"; } if($password == $confirm_password) { // Database Connection required require "db_conncect.php"; // We Now connect to the Dabase and insert the Form input details //------- ### ENTERING ALL INFORMATION INTO THE DATABASE BELOW ### --------// // 1. Create a database connection $con = mysql_connect("localhost","root",""); // <-- THIS IS WHERE YOU " CAN CHANGE " THE USERNAME IS "root", PASSWORD IS "" ONLY. if (!$con) { die('Database connection failed could not connect: ' . mysql_error()); } // 2. Select a database to use $db_select = mysql_select_db("registernow_2012",$con); // <-- THE "registernow_2012" IS THE NAME OF THE DATABASE. if (!$db_select) { die('Database selection failed could not connect: ' . mysql_error()); } mysql_select_db("registernow_2012", $con); // <-- THE "registernow_2012" IS THE NAME OF THE DATABASE TO BE CONNECTED. // <-- THE `registernow_2012` IS THE NAME OF THE DATABASE TO BE CONNECTED.... `visitors` IS THE TABLE WITH ALL THE FIELDS WITHI IN THE DATABASE. $sql="INSERT INTO `registernow_2012`.`users` ( `id` , `name` , `username` , `$enc_password` , `confirm_password` ) VALUES ( NULL , '$_POST[name]', '$_POST[username]', '[$enc_password]', '$_POST[confirm_password]' )"; if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } // 3. Close Connection mysql_close($con); header("Location: index.php"); // <-- THIS IS WHERE YOU CAN CHANGE THE "Location: Thank you / Index page" of the THANK YOU PAGE. } else { echo "<h2><center>PASSWORDS MUST MATCH!!!!!</center></h2><br>"; } } //echo "<h2><center>WORKING!!!!</center></h2>"; } else echo "<h2><center>ALL FEILDS MUST BE COMPLETED</center></h2>"; } //Ending of full IF Statment ?> <!DOCTYPE html> <html lang='en'> <head> <title>THE FORM MY WAY NOW</title> </head> <div id='centerstage'> <form name="myform" action="workingitoutproperly.php" method="POST"> <p> <label>Name</label><br> <input type='text' name='name' value=''><br> <label>UserName</label><br> <input type='text' name='username' value=''><br> <label>Password</label><br> <input type='password' name='password' value=''><br> <label>Re-Enter Password</label><br> <input type='password' name='confirm_password' value=''><br> <br> <input type='submit' name='submit' value='REGISTER NOW!!'> </p> </form> </div> </html> Similar TutorialsHy 2 all, I have some questions about password security that I haven't been able to find an answer yet. Hopefully you guys know. Here it goes: 1. Is it better to hash(sha2) the password and then salt it or salt it and than hash it ? 2. I'm guessing that using a random salt is better than the same salt used for every password. 3. How can you generate a different random salt for each password ? I mean how will the login page know which random salt to mix with the hashed user inserted password and then to compare it with the password stored in the db. (an example would be great(for both: generating and authentication) 4. I saw some codes in which the salt and/or hash and/or password was split into two (ex: hash.salt1a.password.salt1b or password1a.salt.password1b or salt.hash1a.password.hash1b etc.) Is this a good idea ? Is it really more secure ? If so which would be more secure (splitting the password, the hash or the salt) ? 5. Is double hashing (ex: (sha1(md5($password))) any good ? 6. I've been reading something about password salt and pepper ?? What exactly is pepper ? Is it some sort of second salt ? If somebody could enlighten me about these questions, that would be great. Thanks in advance! I am reworking some code from a password authentication I did a long long time ago. The original code is using SHA1() function to encrypt the passwords for storage in the MySQL database. Is that still considered the way to go, or should I be using a different method for encrypting the little buggers? Thanks I'm sorry if this seems like a stupid question, but I'm having trouble with this encryption and I'm a real noob at PHP. This is for a registration form going into a mysql DB for integration with a gaming server that must use a Whirlpool Salt Hash encryption. These are the variables for my form: userPassword userName userEmail This was my original encryption script (MD5) Code: [Select] $_POST['userPassword'] = md5($_POST['userPassword']); This is the function that I am given to integrate into my website system: Code: [Select] function encryptPassword($password) { $salt = substr(hash('whirlpool', uniqid(rand(), true)), 0, 12); $hash = hash('whirlpool', $salt . $password); $saltPos = (strlen($password) >= strlen($hash) ? strlen($hash) : strlen($password)); return substr($hash, 0, $saltPos) . $salt . substr($hash, $saltPos); } I've tried inserting the variable $_POST['userPassword'] in place for $password, but it gives me errors... I'm stuck here, could someone show me how to properly integrate this? I think the problem isn't getting the password into the function but catching the returned variable Sorry for my noobishnness, -Nolam EDIT: I'm also given this for the login page to check the hash. If you could help me with this it would be greatly appreciated to. Thanks!!! Code: [Select] function checkPassword($realPass, $checkPass) { //check for old encryption (md5 or whirlpool) if (strlen($realPass) == 32 || strlen($realPass) == 128) { $hash = (strlen($realPass) == 32 ? md5($checkPass) : hash('whirlpool', $checkPass)); if ($realPass == $hash) { // change password to new encryption? return true; } else return false; } // xAuth 2 encryption $saltPos = (strlen($checkPass) >= strlen($realPass) ? strlen($realPass) : strlen($checkPass)); // extract salt $salt = substr($realPass, $saltPos, 12); $hash = hash('whirlpool', $salt . $checkPass); return substr($hash, 0, $saltPos) . $salt . substr($hash, $saltPos) == $realPass; } (Main Objective) I need this login class to encrypt the password before it sends it to the database for login verification. (Alternative Solution) Force a login with just the username and captcha no password.. This is the original working script.. <? session_start(); include "config.php"; global $c; include "data.php"; global $config; require('funciones.php'); if ($_POST['username']) { session_start(); if($_POST['code']!=$_SESSION['string']){ header("Location: login.php?error=1"); } //Comprobacion del envio del nombre de usuario y password $username=uc($_POST['username']); $password=uc($_POST['password']); if ($password==NULL) { header("Location: login.php?error=2"); }else{ $query = mysql_query("SELECT username,password FROM tb_users WHERE username = '$username'") or die(mysql_error()); if(mysql_num_rows($query) == 0) { header("Location: login.php?error=3"); } else { $data = mysql_fetch_array($query); if($data['password'] != $password) { header("Location: login.php?error=4"); }else{ $query = mysql_query("SELECT username,password FROM tb_users WHERE username = '$username'") or die(mysql_error()); $row = mysql_fetch_array($query); $nicke=$row['username']; $passe=$row['password']; //90 day cookie setcookie("usNick",$nicke,time()+7776000); setcookie("usPass",$passe,time()+7776000); $lastlogdate=time(); $lastip = getRealIP(); $querybt = "UPDATE tb_users SET lastlogdate='$lastlogdate', lastiplog='$lastip' WHERE username='$nicke'"; mysql_query($querybt) or die(mysql_error()); header("Location: members.php"); // echo "Has sido logueado correctamente ".$_SESSION['s_username']." y puedes acceder al index.php."; // echo "<script>location.href='index.php';</script>"; ?> <META HTTP-EQUIV="REFRESH" CONTENT="0;URL=members.php"> <? } } } } ?> <div class="heading">Login</div><br /> <? if($_GET['error'] == 1) { print "<b>Error</b> - Wrong Captcha Code<br /><br/>"; } if($_GET['error'] == 2) { print "<b>Error</b> - Please supply a password<br /><br/>"; } if($_GET['error'] == 3) { print "<b>Error</b> - Invalid Username<br><br>"; } if($_GET['error'] == 4) { print "<b>Error</b> - Invalid Password<br /><br />"; } ?> <form action="login.php" method="post"> <table> <tr> <td class="midtext">Username:</td> <td> <input type="text" name="username" size="25" class="form" autocomplete="off"></td> </tr> <tr> <td class="midtext">Password:</td> <td> <input type="password" name="password" size="25" class="form" autocomplete="off"></td> </tr> <tr> <td class="midtext" valign="top">Security Code:</td> <td class="midtext"> <img src="image.php" onclick="this.src='image.php?newtime=' + (new Date()).getTime();">(Click to reload)<br /> <input type="text" name="code" size="17" maxlength="17" autocomplete="off" class="form"></td> </tr> <tr> <td></td> <td align="right"> <input type="submit" value="Login" name="loginsubmit" class="form"></td> </tr> </table> </form> Let me know if you need any files... hi im testing out my site and basically when users register their passwords and encrypted for security obs however when i go to test the login with the exact same password as the one used to register the system detects it as invalid when its not, I've literally copy pasted the password so that i was sure it was the same therefore the issue is within the encryption does anyone have an idea how to overcome this I've tested changed names of variables but nothing seems to help I've even got an error reporting function but no error is detected
<?php error_reporting(E_ALL); include_once("conninfo2.php"); if(isset($_POST['username']) && trim($_POST['username']) != ""){ $username = strip_tags($_POST['username']); $password = $_POST['password']; $hmac = hash_hmac('sha512', $password, file_get_contents('textfiles/key.txt')); $stmt1 = $db->prepare("SELECT usersid, password FROM login WHERE username=:username AND activated='1' LIMIT 1"); $stmt1->bindValue(':username',$username,PDO::PARAM_STR); try{ $stmt1->execute(); $count = $stmt1->rowCount(); if($count > 0){ while($row = $stmt1->fetch(PDO::FETCH_ASSOC)){ $uid = $row['usersid']; $hash = $row['password']; } if (crypt($hmac, $hash) === $hash) { $db->query("UPDATE login SET lastlog=now() WHERE usersid='$uid' LIMIT 1"); $_SESSION['uid'] = $uid; $_SESSION['username'] = $username; $_SESSION['password'] = $hash; setcookie("usersid", $uid, strtotime( '+30 days' ), "/", "", "", TRUE); setcookie("username", $username, strtotime( '+30 days' ), "/", "", "", TRUE); setcookie("password", $hash, strtotime( '+30 days' ), "/", "", "", TRUE); echo 'Valid password<br />'.$_SESSION['uid'].'<br />'.$_SESSION['username'].'<br />'.$_SESSION['password'].' <br />'.$_COOKIE['usersid']; /*header("location: index.php");*/ exit(); } else { echo 'Invalid password Press back and try again<br />'; exit(); } } else{ echo "A user with that email address does not exist here"; $db = null; exit(); } } catch(PDOException $e){ echo $e->getMessage(); $db = null; exit(); } } ?> I don't know if my password encrytion has been done correctly / is actually secure. I don't have anything valuable at the moment that people would care to hack, but in the future I want to be absolutely certain I am doing it right.
This is my process, I am storing it as Varchar(255), did a cost test and 9 was my result
$hash = password_hash($passsword, PASSWORD_BCRYPT, array("cost"=>9));I was told I don't need a salt since it is included in the password_hash function Also I noticed most of the hashes if not all start like this, why is that? $2y$09$Thanks for any help Edited by moose-en-a-gant, 08 January 2015 - 01:51 PM. hello everyone i'm new to PHP and i need your help. I'm developing a code which implements shannon-fano encryption algorithm with php. But i have problems with my function. Basicly i try to do this: 1.Specofy a string to be coded. 2.Count the number of occurences of a character and write it in assoc array like this : "A"=>4,"B"=>2 etc. then i copy this array 3.After i have the array i sort it descending. 4.Divide the given array into two arrays where the sum of the values is almost equal.In the Copied array i set the value of the elements which fit into the fisrt divided array with 0 the rest with 1. 5.Each of the divided arrays i divide with recursion again until every symbol is into different array.and add to the value in the copied array 0 or 1; 6.I try to print the copied array. here is my function which doesnt work and gives a lot of errors function divide_array($array) { $sum=0; $mid=array_sum($array)/2; foreach($array as $k=>$v) { if($sum<$mid){ $sum=$sum+$array[$k]; $up[$k]=$array[$k]; $codeArr[$k]=0; } else { $down=array_slice($array,$k+1); $codeArr[$k]=1; } } divide_array($up); divide_array($down); echo "<pre>"; print_r($codeArr); echo "</pre>"; } i appreciate any help PS:I know this can be done easier with trees but i don't understand them. Alright, wasn't quite sure how to summarize this in the title, but I want to: Check if a user status is "active" or not based on the UserName input. I have a table witch holds: Code: [Select] VarChar Username Var CharPassWord int Active Ted TedsPW 1 something like the above(assuming it formatted correctly. In my php script I will want to input a variable for Username to check for: inputUN in this example would be "Ted". $UserNameToCheck = $_GET['inputUN']; Then I want to check for that UserName in the database, if it exists, I want pull the value for the "Active" field for just that UserName and echo it. Thanks for any help. Well this sounds weird, but it happens. I have an itemshop script, and I wanna code a system that automatically delete the database entry once the variable item amount falls to 0. However, this doesnt happen when I check phpmyadmin, and the item remains in the database even after the amount becomes 0. In fact, the amount can become negative at times, which annoys me. The code of deleting sql entry looks like this: if($continue == "yes"){ $query = "SELECT * FROM ".$prefix."user_inventory WHERE item_owner = '$loggedinname' AND item_name = '$item_name'"; $result = mysql_query($query); $num = mysql_numrows($result); $item_data = mysql_fetch_array($result); $item_amount = $item_data['item_amount']; $newquantity = $item_amount - $quantity; $query = "UPDATE ".$prefix."user_inventory SET item_amount = '$newquantity' WHERE item_owner = '$loggedinname' AND item_name = '$item_name'"; $result = mysql_query($query); if($newquantity == "0"){ $query = "DELETE FROM ".$prefix."user_inventory WHERE item_owner = '$loggedinname' AND item_name = '$item_name'"; $result = mysql_query($query); } What part of the codes should I edit to fix this issue? Thanks. I am using php to upload a file to my server, and at the same time inserting the files name and url into my mysql database.
$sql = "UPDATE uploads SET name = '$name', url='$target_path'"; $statement = $dbh->prepare($sql); $statement->execute();This is working, however, when I upload a new file, rather than making a new entry in my database, it just overwrites the first one. I'm quite new at mysql so was wondering how I would make it add new entrys instead of overwriting the current one? Having a little problem with passwords, they are stored clear text and not encrypted because its for an assignment and I need to prove in the write up that users can change their passwords. Anyway when I register a user with a username and a password of say Password1, I can still login with PASSword1 or any other variation of upper and lower case characters! This is my select statement: Code: [Select] $qry = "SELECT * FROM users WHERE username='$username' AND password='$password'"; Just wondering if there is anything that can be done to this, I read somewhere about using === but that doesn't seem to be fixing the problem, it just causes the query to fail! Using MySQL if thats any help. Thanks Hello, I've got the following code, who doesn't change the password on the database: <?php include "connect.php"; session_start(); session_register("session"); $new_password = $_POST['new_password']; $new_password_again = $_POST['new_password_again']; if(!isset($session['connection_status'])) { echo "<center><font face='Verdana' size='2' color=red>Sorry, Please login and use this page </font></center>"; exit;} ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Change Password</title> <script type="text/javascript" src="js/jquery.min.js"></script> <script type="text/javascript" src="js/jquery.ketchup.js"></script> <script type="text/javascript" src="js/jquery.ketchup.messages.js"></script> <script type="text/javascript" src="js/jquery.ketchup.validations.basic.js"></script> <script language="javascript" type="text/javascript" src="niceforms.js"></script> <link rel="stylesheet" type="text/css" media="all" href="niceforms-default.css" /> <link rel="stylesheet" type="text/css" media="screen" href="css/jquery.ketchup.css" /> </head> <body> <div id="container"> <fieldset> <legend>Change Password</legend> <p>Please enter your new password below</p> <form method="post" action="change_password.php" name="changepassword" id="changepassword"class="niceform" > <dl> <dt><label for="new_password">New Password:</label><br /></dt> <dd><input type="password" name="new_password" id="new_password" class= "validate(required, rangelength(4,30))" /></dd> </dl> <dl> <dt><label for="new_password_again">Password (again):</label><br /></dt> <dd><input type="password" name="new_password_again" id="new_password_again" class= "validate(required, match(#new_password))" /></dd> </dl> <dl> <dt> <dd><input type="submit" name="change_password" id="change_password" value="Change Password" /> <input type="reset" name="reset" id="reset" value="Reset" /></dd> </dt> </dl> </form> </fieldset> </div> <?php if (empty($_POST['new_password']) && empty($_POST['new_password_again'])) { ?> <div id="container"> <form method="post" action="<?php echo $_SERVER['REQUEST_URI']; ?>" name="loginform" id="loginform" class="niceform" > <fieldset> <legend>Error</legend> <p>Please go back and complete all the fields in the form</p> <p>Click <a href="index.php">here</a> to try again.</p> </fieldset> </form> </div> <?php } else { $db_new_password=md5(mysql_real_escape_string($new_password)); $status = "OK"; $msg=""; if ( strlen($new_password) < 3 or strlen($new_password) > 10 ) { $msg=$msg."Password must be more than 3 characters in length and maximum 10 characters in length<BR>"; $status= "NOTOK"; } if (strcmp( $new_password,$new_password_again ) !=0) { $msg=$msg."Both passwords do not match<BR>"; $status= "NOTOK"; } if($status<>"OK") { echo "<font face='Verdana' size='2' color=red>$msg</font><br><center><input type='button' value='Retry' onClick='history.go(-1)'></center>"; } else { if(mysql_query("update users set password='$db_new_password' where userid='$session[userid]'")) { echo "<font face='Verdana' size='2' ><center>Thanks <br> Your password changed successfully. Please keep changing your password for better security</font></center>". $new_password ; } } } ?> <script type = "text/javascript"> $(document).ready(function() { $('#changepassword').ketchup(); }); </script> </body> </html> Hi, im having trouble with the below code which is used in case user forgets password. If i enter username and ANY email, it will send there "Username" and "Password". off course i just want it to be sent only to existing email in db. any ideas? Thank you. <? include("fns.php"); include "config.php"; if(isset($_POST['Submit'])){ //1. Check if form fields are filled in if(!filledin($_POST)){ header( "Location:Messages.php?msg=7" ); exit(); } $name=$_POST['name']; $em=$_POST['mail']; //2. Check if entered name exist $query="Select pw from user where uname='$name'" or die(mysql_error()); $result= mysql_query($query); if(mysql_num_rows($result)>0){ for ($i=0; $i<mysql_num_rows($result); $i++) { $row = mysql_fetch_assoc($result); $pass=$row['pw']; $to="$em\r\n"; $from="From: \r\n"; $msg="Password:$pass\r\n"; $msg .="Username:$name\r\n"; $msg .="Your login information\r\n"; $subject=" Your Login Password\r\n"; } }else{ header( "Location:Messages.php?msg=8" ); exit(); } //4. Send password to user if(mail($to,$subject,$msg,$from)){ header( "Location:Messages.php?msg=9&email=<?php echo $em; ?>" ); exit(); //echo "Please click here to log"; }else{ header( "Location:Messages.php?msg=10"); exit(); } } hi folks I have a problem with the code to change the password, it shows the message all time when I send the form: old password dont match! <?php session_start(); $user = $_SESSION['first_name']; if ($user) { //user is logged in if ($_POST['submit']) { //check fields $oldpassword = md5($_POST['oldpassword']); $newpassword = md5($_POST['newpassword']); $repeatnewpassword = md5($_POST['repeatnewpassword']); //check password against db //connect db $connect = mysql_connect("*******","****","****") or die(""); mysql_select_db("****") or die(""); $queryget = mysql_query("SELECT password FROM users WHERE username='$user'") or die("Query didnt work !!!"); $row = mysql_fetch_assoc($queryget); $oldpassworddb = $row['password']; //check password if ($oldpassword==$oldpassworddb) { //check to new password if ($newpassword==$repeatnewpassword) { //success //change password in db $querychange = mysql_query("UPDATE users SET password='$newpassword' WHERE username='$user'") or die (""); session_destroy(); die("YOUR PASSWORD HAS BEEN CHANGED.<a href='login_form.html'>RETURN</a> TO THE LOGIN PAGE"); } else die("new password dont match"); } else die("old password dont match"); } else { echo" <form action='changepassword.php' method='POST'> Old password: <input type='text' name='oldpassword'><br/> New password: <input type='password' name='newpassword'><br/> Repeat new password: <input type='password' name='repeatnewpassword'><br/> <input type='submit' name='submit' value='change password'> </form>"; } } else echo("YOU MUST BE LOGGED IN!!!!.<br><a href='login_form.html'>RETURN</a> TO THE LOGIN PAGE"); ?> please help thanks! Hi there, I've set up a basic password change that sends an email to the client when they change their password. The email notify's the client that their password has been changed and what the password is. The current problem I'm receiving is that when the user changes their password the message confirms that an email has been sent however, the email never arrives. The original email only arrives when the client changes their password again and they receive their first password change not their new password change. Can you help?? my code is below: Code: [Select] <?php $host="localhost"; // Host name $username="root"; // Mysql username $password="*******"; // Mysql password $db_name="testpwreset"; // Database name //Connect to server and select database. $con=mysql_connect("$host", "$username", "$password"); mysql_connect("$host", "$username", "$password") or die("cannot connect to server"); mysql_select_db("$db_name") or die("cannot select DB"); // value sent from form $email_to=$_POST['email_to']; $old_password=$_POST['old_password']; $new_password=$_POST['new_password']; $new_password2=$_POST['new_password2']; if ($new_password != $new_password2) {die("Your passwords do not match");} // table name $tbl_name=members; mysql_query("UPDATE $tbl_name SET password = '$new_password' WHERE email = '$email_to' AND password = '$old_password'"); // retrieve password from table where e-mail = $email_to(*****@gmail.com) $sql="SELECT password FROM $tbl_name WHERE email='$email_to' AND password = '$old_password'"; $result=mysql_query($sql); // if found this e-mail address, row must be 1 row // keep value in variable name "$count" $count=mysql_num_rows($result); // compare if $count =1 row if($count==1){ $asdf=mysql_query("UPDATE $tbl_name SET password = '$new_password' WHERE email = '$email_to' AND password = '$old_password'"); $rows=mysql_fetch_array($result); // keep password in $your_password $your_password=$rows['password']; // ---------------- SEND MAIL FORM ---------------- // send e-mail to ... $to=$email_to; // Your subject $subject="Your Tafe FTP Password"; // From $header="from: your name \<your email\>"; // Your message $messages= "Your password for login to the Orange Tafe IT Ftp Server is: $your_password \r\n"; // send email $sentmail = mail($to,$subject,$messages,$header); } // else if $count not equal 1 else { echo "Cannot find your email in our database"; } // if your email succesfully sent if($sentmail){ echo "Your Password Has Been Sent To Your Email Address."; } else { echo "Cannot send password to your e-mail address"; } ?> <?php if (isset($_POST['reset-submit'])) { $selector = $_POST['selector']; $validator = $_POST['validator']; $password = $_POST['password']; $password2 = $_POST['password2']; // probably better to check this earlier if (empty($password) || empty($password2)) { header("Location: ../create-new-password.php?newpassword=empty&selector=$selector&validator=$validator"); } elseif ($password !== $password2) { header("Location: ../create-new-password.php?newpassword=passwordsnotmatch"); } $currentDate = date("U"); require "dbh.inc.php"; $sql = "SELECT * FROM reset_password WHERE selector=? AND expires >= $currentDate"; $stmt = mysqli_stmt_init($conn); if (!mysqli_stmt_prepare($stmt, $sql)) { echo "SQL error 1"; exit(); } else { mysqli_stmt_bind_param($stmt, 'ss', $selector, $currentDate); mysqli_stmt_execute($stmt); $result = mysqli_stmt_get_result($stmt); if (!$row = mysqli_fetch_assoc($result)) { echo 'You need to re-submit your reset request.'; exit(); } else { $tokenBin = hex2bin($validator); $tokenCheck = password_verify($tokenBin, $row['token']); if (!$tokenCheck) { echo 'You need to re-submit your reset request.'; exit(); } else { $email = $row['email']; $sql = "SELECT * FROM users WHERE email = $email"; $stmt = mysqli_stmt_init($conn); if (!mysqli_stmt_prepare($stmt, $sql)) { echo "SQL error 2"; exit(); } else { mysqli_stmt_bind_param($stmt, 's', $email); mysqli_stmt_execute($stmt); $result = mysqli_stmt_get_result($stmt); if (!$row = mysqli_fetch_assoc($result)) { echo "SQL error 3"; exit(); } else { $sql = "UPDATE users SET password=? WHERE email=?"; $stmt = mysqli_stmt_init($conn); if (!mysqli_stmt_prepare($stmt, $sql)) { echo "SQL error4 "; exit(); } else { $hashed_password = password_hash($password, PASSWORD_DEFAULT); mysqli_stmt_bind_param($stmt, 'ss', $hashed_password, $email); mysqli_stmt_execute($stmt); $sql = 'DELETE FROM reset_password WHERE email=?'; $stmt = mysqli_stmt_init($conn); if (!mysqli_stmt_prepare($stmt, $sql)) { echo 'SQL error5'; exit(); } else { mysqli_stmt_bind_param($stmt, 's', $email); mysqli_stmt_execute($stmt); header("Location: ../signup.php?newpassword=updated"); } } } } } } } mysqli_stmt_close($stmt); mysqli_close($conn); header('Location: ../reset-password.php?reset=success'); } else { header('Location: ../index.php'); } I always get this errors:
Warning: mysqli_stmt_bind_param(): Number of variables doesn't match number of parameters in prepared statement in C:\xampp\htdocs\php_login_system-master\includes\reset-password.inc.php on line 26
But i dont find the mistake in the Code. Can someone help me please hello everyone, i try to make a registration script and change password script with PIN as security code, registration script was working perfect, but change password script didn't work. here i give a full code for you to review. here link to file Test.7z I hope someone can help and give me information what i'am missing. Hello PhP Freaks forum In the past weeks ive been trying to make a website, where you can register. Everything seems to work except my cherished Change password feature. Everytime you try to change the password, it just resets it to nothing. Here is the code below. <?php if(isset($_SESSION['username'])) { $username = $_SESSION['username']; $lastname = $_SESSION['lastname']; $firstname = $_SESSION['firstname']; $email = $_SESSION['email']; echo " <h4>Options for:</h4> $username <br /> <br /> First name: $firstname <br />Last name: $lastname <br /><br /><h3>Want to change your password:</h3><br /> <form action='?do=option' method='post'> Old password <input type='password' placeholder='Has to be between 5-15 digits' name='password' size='30' value='' /><br /> <br /> New Password<input type='password' placeholder='Has to be between 5-15 digits' name='newpass' size='30' value='' /><br /> <br /> Confirm new password <input type='password' placeholder='Has to be between 5-15 digits' name='passconf' size='30' value='' /><br /> <center></div><input type='submit' value='Submit'/></center></form>"; }else{ echo 'Please login to view your options!'; } $password = $_REQUEST['password']; $pass_conf = $_REQUEST['newpass']; $email = $_REQUEST['passconf']; $connect = mysql_connect("Host", "User", "Password"); if(!$connect){ die(mysql_error()); } //Selecting database $select_db = mysql_select_db("My Database", $connect); if(!$select_db){ die(mysql_error()); } //Find if entered data is correct $result = mysql_query("SELECT * FROM users WHERE username='$username' AND password='$password'"); $row = mysql_fetch_array($result); $id = $row['id']; mysql_query("UPDATE users SET password='$newpass' WHERE username='$user'") ?> And i do know that i dont have a if(Empty($newpass)){ Die(Please fill out the new password) } Or any security on the others, but the problem just seems that it resets the password into nothing Hope i can get this fixed Best Regards William Pfaffe <?php
require_once('upper.php'); require_once('database.php'); echo $error_msg=''; if(isset($_POST['submit'])) { $LoginId=mysqli_real_escape_string($dbc,trim($_POST['LoginId'])); $Password1=mysqli_real_escape_string($dbc,trim($_POST['Password1'])); $Password2=mysqli_real_escape_string($dbc,trim($_POST['Password2'])); $Name=mysqli_real_escape_string($dbc,trim($_POST['Name'])); $Age=mysqli_real_escape_string($dbc,trim($_POST['Age'])); $BloodGroup=mysqli_real_escape_string($dbc,trim($_POST['BloodGroup'])); if(!isset($_POST['Sex'])) { echo 'Please enter Sex<br>'; } else{ $Sex= mysqli_real_escape_string($dbc,trim($_POST['Sex'])); } $Qualification=mysqli_real_escape_string($dbc,trim($_POST['Qualification'])); $ContactNumber=mysqli_real_escape_string($dbc,trim($_POST['ContactNumber'])); $Email=mysqli_real_escape_string($dbc,trim($_POST['Email'])); $Address=mysqli_real_escape_string($dbc,trim($_POST['Address'])); $AboutYourself=mysqli_real_escape_string($dbc,trim($_POST['AboutYourself'])); //$countCheck=count($_POST['checkbox']); //echo $countCheck; //$checkbox=$_POST['checkbox']; //$countCheck=count($checkbox); if(empty($LoginId)){echo 'Please enter Login Id';} elseif(empty($Password1)){echo 'Please enter Password';} elseif(empty($Password2)){echo 'Please confirm Password';} elseif($Password1!==$Password2){echo 'Password didn\'t match';} elseif(empty($Name)){echo 'Please enter Name';} elseif(empty($Age)){echo 'Please enter Age';} elseif(!isset($_POST['Sex'])){} elseif(empty($Qualification)){echo 'Please enter Qualification';} elseif(empty($ContactNumber)){echo 'Please enter Contact Number';} elseif(empty($Email)){echo 'Please enter Email';} elseif(empty($Address)){echo 'Please enter Address';} elseif(empty($AboutYourself)){echo 'Please enter About Yourself';} elseif(!isset($_POST['checkbox'])){ echo 'You have to register at least one activity.';} elseif(!isset($_POST['TermsAndConditions'])){ echo 'You have to agree all Terms and Conditions of Elite Brigade.';} else { require_once('database.php'); $query="select * from registration where LoginId='$LoginId'"; $result=mysqli_query($dbc,$query); if(mysqli_num_rows($result)==0) { $checkbox=$_POST['checkbox']; $countCheck=count($_POST['checkbox']); $reg_id=' '; for($i=0;$i<$countCheck;$i++) { $reg_id=$reg_id.$checkbox[$i].','; $query="insert into activity_participation (LoginId,Title,Date) values ('$LoginId','$checkbox[$i]',CURDATE())"; $result=mysqli_query($dbc,$query) or die("Not Connected"); } $query="insert into registration (LoginId,Password,Name,Age,BloodGroup,Sex,Qualification,ContactNumber,Email,Address,AboutYourself,Activity)values ('$LoginId'[B],SHA('$Password1'),[/B]'$Name','$Age','$BloodGroup','$Sex','$Qualification','$ContactNumber','$Email','$Address','$AboutYourself',',$reg_id')"; $result=mysqli_query($dbc,$query) or die("Not Connect"); echo ' Dear '.$Name.'.<br>Your request has been mailed to admin.<br>Your account is waiting for approval<br>'; $from= 'Elite Brigade'; $to='ankitp@rsquareonline.com'; $subject='New User Registration'; $message="Dear admin,\n\nA new user request for registration. Please check it out.\n\nRegards\nMicro"; mail($to,$subject,$message,'From:'.$from); //header('Location: index.php'); // header('Location: Registration.php'); } else { echo 'Dear '.$Name. ', <br> An account already exist with login-id<b> '.$LoginId.'</b> <br>Please try another login-id'; }} } ?> <html> <head> <script src="jquery-latest.js"></script> <script type="text/javascript" src="jquery-validate.js"></script> <style type="text/css"> * { font-family: Verdana; } label.error { color: white; padding-left: .5em; } p { clear: both; } .submit { margin-left: 12em; } em { font-weight: bold; padding-right: 1em; vertical-align: top; } </style> <script> $(document).ready(function(){ $("#commentForm").validate(); }); </script> </head> <body> <?php echo $error_msg; ?> <form action='<?php echo $_SERVER['PHP_SELF'];?>' id="commentForm" method='post'> <div class="registration_and_activity"> <table border="0" width="380"> <tr><td colspan="2"> <h3>New User?</h3></td></tr> <tr><td width="120"> <em>*</em>Enter Login id</td><td width="150"><input type='text' name='LoginId' minlength="4" value='<?php if(!empty($LoginId))echo $LoginId;?>' /></td></tr> <tr><td> <em>*</em>Enter Password</td> <td><head> <div id="divMayus" style="visibility:hidden">Caps Lock is on.</div> <SCRIPT language=Javascript> function capLock(e){ kc = e.keyCode?e.keyCode:e.which; sk = e.shiftKey?e.shiftKey:((kc == 16)?true:false); if(((kc >= 65 && kc <= 90) && !sk)||((kc >= 97 && kc <= 122) && sk)) document.getElementById('divMayus').style.visibility = 'visible'; else document.getElementById('divMayus').style.visibility = 'hidden'; } </SCRIPT> </HEAD> <input onkeypress='return capLock(event)' type='password' name='Password1' value='<?php if(!empty($Password1))echo $Password1;?>' /></td></tr> <tr><td> <em>*</em>Confirm Password</td><td><input type='password' name='Password2' value='<?php if(!empty($Password2))echo $Password2;?>' /></td></tr> <tr><td width="120"> <em>*</em>Enter Name</td> <td><input type='text' name='Name' value='<?php if(!empty($Name))echo $Name;?>' /></td></tr> <tr><td> <em>*</em>Enter Age</td><HEAD> <SCRIPT language=Javascript> function isNumberKey(evt) { var charCode = (evt.which) ? evt.which : event.keyCode if (charCode > 31 && (charCode < 48 || charCode > 57)) return false; return true; } </SCRIPT> </HEAD> <td><INPUT onkeypress='return isNumberKey(event)' type='text' name='Age' value='<?php if(!empty($Age))echo $Age;?>'/></td></tr> <tr><td> <em>*</em>Enter Blood</td><td><input type='text' name='BloodGroup' value='<?php if(!empty($BloodGroup))echo $BloodGroup;?>' /></td></tr> <tr><td> <em>*</em>Enter Sex</td><td><input type='radio' name='Sex' style='width:16px; border:0;' 'value='Male' />Male <input type='radio' name='Sex' style='width:16px; border:0;' 'value='Female' />Female</td></tr> <tr><td> <em>*</em>Enter Qualification</td><td><input type='text' name='Qualification' value='<?php if(!empty($Qualification))echo $Qualification;?>' /></td></tr> <tr><td> <em>*</em>Contact Number </td><td><input onkeypress='return isNumberKey(event)'type='text' name='ContactNumber' value='<?php if(!empty($ContactNumber))echo $ContactNumber;?>' /></td></tr> <tr><td> <em>*</em>Enter Email</td><td><input type='text' name='Email'class="email" value='<?php if(!empty($Email))echo $Email;?>' /></td></tr> <tr><td> <em>*</em>Enter Address</td><td><input type='text' name='Address' value='<?php if(!empty($Address))echo $Address;?>' /></td></tr> <tr ><td > <em>*</em>About Yourself </td></tr> <tr><td colspan="2"><textarea rows='10' cols='40' name='AboutYourself' /><?php if(!empty($Address))echo $Address;?></textarea></td></tr> <tr><td> <?php echo" <tr><td colspan='2'><em>*</em><b>Select fields for which you want to register</b></td></tr>"; require_once('database.php'); $query="select * from activity"; $result=mysqli_query($dbc,$query); while($row=mysqli_fetch_array($result)){ $Title=$row['Title']; $ActivityId=$row['ActivityId']; echo "<tr><td>$Title</td>"; echo "<td><input type='checkbox' name='checkbox[]' value='$Title' style='width:14px; text-align:right;'/></td></tr>";//value=$ActivityId tells ActivityId variable extracts with name="checkbox" echo "<br/>"; } echo "<td><em>*</em><input type='checkbox' name='TermsAndConditions' style='width:14px; text-align:right;'/></td><td> I agree all <a href='TermsAndConditions.php'>Terms and conditions </a>of Elite Brigade</td></tr>"; echo "<tr><td colspan='2' align='center'><input type='submit' value='Register' name='submit' style='background:url(./images/button_img2.png) no-repeat 10px 0px; width:100px; padding:3px 0 10px 0; color:#FEFBC4; border:0;'/></td></tr><br>"; echo " </td></tr></table> </div> </form> </body> </html>"; require_once('lower.php'); ?> Hi Friends .... I encrypt user password by SHA('$Password') method but now i want to add "Forget Password Module" for which I need to decrypt it first before tell my user but I don't Know how to decrypt it. Please help me........ |