forgot password script

Ask about a PHP problem here.
Post Reply
User avatar
Robbedoesie
Posts: 97
Joined: Thu May 19, 2011 7:37 pm
Location: Enkhuizen, Holland

forgot password script

Post by Robbedoesie »

[/syntax]Hello,
i am working with a forgot password script but i can't get the random password include in the mail and in the database.
I know the random password generator is working alright but it is somehow not reaching the places i have in mind.

forgot_password.php
<?php
include('core/init.inc.php'); 

	   random_string(10);
	   
        
        $submit = $_POST['submit'];
        
        //form data
        $email = $_POST['email'];
        $username = $_POST['username'];
        
        if ($submit) {
            $create = mysql_query("UPDATE user_system SET user_password='$password' WHERE user_name='$username'");
            $emailquery = mysql_query("SELECT user_email FROM user_system WHERE user_email='$email'");
            $emailcheck = mysql_num_rows($emailquery);
            $user = mysql_query("SELECT user_name FROM user_system WHERE user_name='$username'");
            $usercheck = mysql_num_rows($user);
            
            if (($usercheck && $emailcheck) != 0) {
                
                
                //send activation email
                $to = "$email";
                $subject = "Uw nieuwe wachtwoord!";
                $headers = "From: test";
                
				$body = <<<EMAIL
	
	Hallo $username,
	u heeft een ander wachtwoord aangevraagd. Klik op onderstaande link om je wachtwoord te veranderen. 
	<a href='http://robcnossen.nl/login/login.php?us ... sword'></a>
	Uw nieuwe automatisch gegenereerde wachtwoord = $password 
EMAIL;
                
                
                //function to send mail
                mail($to, $subject, $headers, $body);
                die("Uw automatisch gegenereerde wachtwoord is verzonden. Check uw email voor uw nieuwe wachtwoord!");
            }
        else
            echo "Email en/of uw gebruikersnaam is niet gevonden in de database!";
        }
    ?>
    <div id="content">
    <div id="content_txt">
        <form action='vergeten_paswoord.php' method='POST'>
            <h1>Wachtwoord vergeten?</h1><br>
            Gebruikersnaam:<input type="text" name="username" size=25 maxlength=25 /></p>
            Email: <input type="text" name="email" size=25 maxlength=25 /></p>
            <input type="submit" name="submit" VALUE="Send" class="button" /></p>
        </form>
    </div>
    </div>
user.inc.php
<?php
//bestaat de gebruikersnaam in de database
function user_exists($user){
	$user = mysql_real_escape_string($user);
	$total = mysql_query("SELECT COUNT(`user_id`) FROM `user_system` WHERE `user_name` = '{$user}'");
	return (mysql_result($total, 0) == '1') ? true : false;
}
//is de gebruikersnaam en paswoord combinatie correct
function valid_credentials($user, $pass){
	$user = mysql_real_escape_string($user);
	$pass = mysql_real_escape_string($pass);
	
	$total = mysql_query("SELECT COUNT(`user_id`) FROM `user_system` WHERE `user_name` = '{$user}' AND `user_password` = '{$pass}'");
	    
	return (mysql_result($total, 0) == '1') ? true : false;
}
function is_active($user){
	$user = mysql_real_escape_string($user);
	
	$sql = "SELECT
			COUNT(`user_activations`.`user_id`)
			FROM `user_system`
			INNER JOIN `user_activations`
			ON `user_system`.`user_id` = `user_activations`.`user_id`
			WHERE `user_system`.`user_name` = '{$user}'";
			
	$result = mysql_query($sql);
	return (mysql_result($result, 0) == '0') ? true : false;
}
function activate_account($aid){
		$aid = mysql_real_escape_string($aid);
		
		mysql_query("DELETE FROM `user_activations` WHERE `activation_code` = '{$aid}'");
		echo mysql_error();		
}

//forgot password 
function random_string($length){
	$charset = array_merge(range('a', 'z'), range('A', 'Z'), range(0, 9));
	
	shuffle($charset);
	$password = array_slice($charset, 0, $length);
	return implode('', $password);
}
//voegt een gebruiker toe aan de database
function add_user($user, $email, $pass){
	$user  = mysql_real_escape_string(htmlentities($user));
	$email = mysql_real_escape_string($email);
	$pass  = sha1($pass);
	
	$charset = array_flip(array_merge(range('a', 'z'), range('A', 'Z'), range(0, 9)));
	$aid = implode('', array_rand($charset, 10));
	
	$body = <<<EMAIL
	
	Hallo,
	dank voor het registreren, voordat je gaat inloggen is het nodig dat je je account gaat activeren.
	omdat de doen kan je gewoon op deze link klikken, http://www.robcnossen.nl/login/activated.php?aid={$aid}
EMAIL;

mail($email, 'je nieuwe account in robbcnossen.nl', $body, 'From: test@test.nl');	
	
	mysql_query("INSERT INTO `user_system` (`user_name`, `user_password`, `user_email`) VALUES ('{$user}', '{$pass}', '{$email}')");
	$user_id = mysql_insert_id();
	mysql_query("INSERT INTO `user_activations` (`user_id`, `activation_code`) VALUES ('{$user_id}', '{$aid}')");
}

?>
Hopefully someone can help me.
Thanks
P.s. I tried to highlight the position in the user.inc.php where the forgotten password script is, but it didn't work. I posted the whole script because maybe the forgot password script is standing on the wrong position if that is possible? I hope that you can find the forgot password part
janvier123
Posts: 23
Joined: Tue Apr 17, 2012 6:25 am

Re: forgot password script

Post by janvier123 »

I dont see $password as a var anywhere
maybe you forgot to add
$password = random_string(10);

thats the only error i see at this time
User avatar
Robbedoesie
Posts: 97
Joined: Thu May 19, 2011 7:37 pm
Location: Enkhuizen, Holland

Re: forgot password script

Post by Robbedoesie »

Thanks for your answer janvier123,
somehow now i get the message; Fatal error: Call to undefined function random_string() in /data/home/cnos01/domains/robcnossen.nl/public_html/login/vergeten_paswoord.php on line 13. I include the user.inc.php with the init.inc.php but the function is not called in the vergeten_paswoord.php page. I don't see why.
This is the init.inc page;
<?php 
session_start();
$exceptions = array('register', 'login', 'activated', 'vergeten_paswoord', 'nieuwwachtwoord');
$page =  substr(end(explode('/', $_SERVER['SCRIPT_NAME'])), 0, -4);

$connection = mysql_connect("localhost","username","password");
if (!$connection) {
	die("Database connection failed: " . mysql_error());
}
$db_select = mysql_select_db("database",$connection);

$path = dirname(__FILE__);

include("{$path}/inc/user.inc.php");
if (!$db_select) {
	die("database selection failed: " . mysql_error());
}
if (isset($_COOKIE['username'], $_COOKIE['password']) && isset($_SESSION['username']) === false){
	if (valid_credentials($_COOKIE['username'], $_COOKIE['password'])){
		$_SESSION['username'] = htmlentities($_COOKIE['username']);
		setcookie('username', $_COOKIE['username'], time() + 684800);
		setcookie('password', $_COOKIE['password'], time() + 684800);
	}
}
if (in_array($page, $exceptions) === false){
	if (isset($_SESSION['username']) === false){
		header('location: login.php');
		die();
	}
}

?>
It is also called without the password var.

I thought that it would take the password var out of the function itself, but maybe it isn't. Hopefully we get the random_password function working and then we will see.

Thanks for your time,
Robbedoesie
janvier123
Posts: 23
Joined: Tue Apr 17, 2012 6:25 am

Re: forgot password script

Post by janvier123 »

Not a real fan of using { } tags
I would write
include ($path."/inc/user.inc.php");
as for the random_string, you are returning a array
http://php.net/manual/en/function.implode.php

Fixed function random_string
//forgot password
function random_string($length)
{
        $charset = array_merge(range('a', 'z'), range('A', 'Z'), range(0, 9));
        shuffle($charset);
        $password = array_slice($charset, 0, $length);
	$return[0] = implode('', $password);
        return $return[0];
}
test
echo random_string(10);
this is my random_string function
function createSn($length, $characters='ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789')
{
	// ---------------------------------------------------------------------
// create_sn
// Example: create_sn(5,'abcd1234') => returns something like: '2b4d3'
// echo createsn(15,'ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789')
// ---------------------------------------------------------------------

	if ($characters == ''){ return ''; }
	$chars_length = strlen($characters)-1;
	
	mt_srand((double)microtime()*1000000);
	
	$pwd = '';
	while(strlen($pwd) < $length){
		$rand_char = mt_rand(0, $chars_length);
		$pwd .= $characters[$rand_char];
	}
	
	return $pwd;

}

User avatar
Robbedoesie
Posts: 97
Joined: Thu May 19, 2011 7:37 pm
Location: Enkhuizen, Holland

Re: forgot password script

Post by Robbedoesie »

Thanks janvier123, it all is working now, with the $password = random_string(10);.

Should i now be able to log in with the random password? I can't log in with the random password, or should i first create a new password page?
janvier123
Posts: 23
Joined: Tue Apr 17, 2012 6:25 am

Re: forgot password script

Post by janvier123 »

If the users asks for a password change, you can either send a email with new password and update the old one in the DB
and to protect you passwords you can store them into a MD5 hash

And i got this old (2004) login / register / forgot script, maybe it can help you
(Its not written by me)

http://www.scampiml.com/logindinges.zip
User avatar
Robbedoesie
Posts: 97
Joined: Thu May 19, 2011 7:37 pm
Location: Enkhuizen, Holland

Re: forgot password script

Post by Robbedoesie »

The new password is send by an email and updated in the DB, but now you mention it is not protected. I gonna work on that.

Thanks for sharing the logindinges. It looks very professional and easy to use. I think that i can learn from it, the comments are in a understandable language.
janvier123
Posts: 23
Joined: Tue Apr 17, 2012 6:25 am

Re: forgot password script

Post by janvier123 »

i know you would understand it, iam dutch also :)
Post Reply