weird issue PASSWORD RESET!

Ask about general coding issues or problems here.

Moderators: macek, egami, gesf

jay93
New php-forum User
New php-forum User
Posts: 5
Joined: Wed Feb 27, 2013 9:53 am

weird issue PASSWORD RESET!

Postby jay93 » Wed Feb 27, 2013 9:55 am

Hi, i m trying to write a code for resetting password. I want this code to show in on the log in page (and the user should be able to open it without being logged in),,, however the problem i am facing is, whenever i open my recover form thus, localhost/pass.php , my recover form has a field for email and security question, ) it just shows the login page, which is localhost/login.php... i'm stuck on this now for days, and nothing seems to improve...


and just to make helping easier, i'm planning to implement a recover function thus:
1. when the user clicks on forgot password on localhost/login.php without already being logged in, it should take them to a page,
pass.php (displaying an email and security question)...

2.and when the users enter both( confirm if they exist in the sql table), then redirect to another form reset.php which shows two fields for "Enter new password" and "Confirm password", and when user enters both, his password is updated in the database...

Pass.php has a template pass_form.php
and reset.php has a template reset_form.phpp


//code for pass.php:


<?php


// configuration
require("../includes/config.php");

if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["forgotpassword"]))
apologize("Please enter email address.");

if (empty($_POST["security"]))
apologize("Please enter your security key.");

$email = $_POST["forgotpassword"];
if(!(filter_var($email, FILTER_VALIDATE_EMAIL)))

apologize("Please enter a valid email such as example@domain.com");

//check if email and securitykey exist in users table

$check= query("SELECT id, security FROM users WHERE email = ?", $_POST["forgotpassword"]);
if ($check === false)
apologize("No such user in database");


render("reset.php", ["title" => "Reset Password", "check" => $check]);

}

else render("login_form.php", ["title" => "Login"]);



?>


3. another problem is when i log in, and then i open localhost/pass.php, it always keeps on rendering the above template called login_form.php( which is linked to the controller login.php...) instead of displaying the pass_form.php
template...
/// pass_form.php is as follows:

<form action="pass.php" method="post">
<fieldset>
<div class="control-group">
<input name="forgotpassword" placeholder="Email" type="text"/>
</div>
<div class="control-group">
<input name="security" placeholder="Security Keyword" type="text"/>
</div>
<div class="control-group">
<button type="submit" class="btn">Reset</button>
</div>
</fieldset>
</form>





RENDER() is a function as follows


function render($template, $values = [])
{
// if template exists, render it
if (file_exists("../templates/$template"))
{
// extract variables into local scope
extract($values);

// render header
require("../templates/header.php");

// render template
require("../templates/$template");

// render footer
require("../templates/footer.php");
}

// else err
else
{
trigger_error("Invalid template: $template", E_USER_ERROR);
}

seandisanti
php-forum Fan User
php-forum Fan User
Posts: 838
Joined: Mon Oct 01, 2012 12:32 pm

Re: weird issue PASSWORD RESET!

Postby seandisanti » Wed Feb 27, 2013 10:21 am

The algorithm i use for forgotten passwords is like this:
When visitor clicks forgot_pass, generate a token and an expiration for it 24 hours out.
Store those values in different fields in your user table for that user.
Send an email to the user containing a reset link, which has the token appended to the url as a $_GET When they go to reset the password, have your update statement include the token, and expiration date fields. For example, your query would be like....

$sql = "UPDATE user SET password = '" .$hashedPass ."', token=NULL,token_expire = NULL WHERE email = '".$email."' AND token_expire > '". strftime("%Y-%m-%d %H:%M:%S",time())."' AND token = '".$token."'";

jay93
New php-forum User
New php-forum User
Posts: 5
Joined: Wed Feb 27, 2013 9:53 am

Re: weird issue PASSWORD RESET!

Postby jay93 » Wed Feb 27, 2013 10:36 am

thanks, could you please write a detailed code, on how to generate token, and other aspects??i m new to php and i struggled a lot to make the current one...

seandisanti
php-forum Fan User
php-forum Fan User
Posts: 838
Joined: Mon Oct 01, 2012 12:32 pm

Re: weird issue PASSWORD RESET!

Postby seandisanti » Wed Feb 27, 2013 11:13 am

No problem; here's a couple of functions to get you started. you can add more or better encryption (sha1 etc) than i do with the generate_hash function, but the method of encrypting and salting is pretty standard, regardless of the encryption used to generate your hash. In the project I used these functions in, I had them all contained in a class User, which also contained functions to search for user etc, which are called within the code here. I'll leave front end and search functions up to you, and will be happy to answer any specific questions you have about the implementation

Code: Select all


public static function forgot_pass($email="")
    {
        GLOBAL 
$database;
        
//  1. When your user requests a password reset, generate a token and calculate its expiry date
        
$arecord=self::find_by_email($email);
        
$token=self::generate_hash($arecord['email']);
        
$expire strftime("%Y-%m-%d %H:%M:%S",time()+3600*24);
        
//  2. Store the token and its expiry date in separate columns in your users table for that user
        
$database->query("UPDATE user set token = '{$token}',token_expire='{$expire}' WHERE email = '{$arecord['email']}'");
public static function 
generate_hash($value)
    {
        
$salt="";
        while (
strlen($salt)<8)
        {
            
$salt .= dechex(mt_rand(0,15));
        }
        return (
md5($value.$salt).$salt);
    }
    public static function 
reset_pass_token($newPass,$token,$email)
    {
        GLOBAL 
$database;
        
$hashedPass self::generate_hash($newPass);
        
$sql "UPDATE user SET password = '" .$hashedPass ."', token=NULL,token_expire = NULL WHERE email = '".$email."' AND token_expire > '"strftime("%Y-%m-%d %H:%M:%S",time())."' AND token = '".$token."'";
        
$database->query($sql);
    }

 

jay93
New php-forum User
New php-forum User
Posts: 5
Joined: Wed Feb 27, 2013 9:53 am

Re: weird issue PASSWORD RESET!

Postby jay93 » Thu Feb 28, 2013 2:16 am

thanks for sharing your code, i really appreciate your help... :) however, i would also like to seek your help in knowing what's wrong with my current work, so that i don't repeat the same mistakes in future...

from my first post, i spoke of the problem of being automatically redirected to the login page when i opened pass.php, i got that one solved, but now i'm stuck with another problem... is there a way i can pass the values in $check from pass.php to a controller file (reset.php)??? i'm facing this problem because the render function i'm using in this page (and on other pages too) works only for templates and not for controllers...
after a few changes, my pass.php looks thus:

Code: Select all

<?php


  // configuration
    require("../includes/constants.php");
    require("../includes/functions.php");
   
     if ($_SERVER["REQUEST_METHOD"] == "POST")
  {
     if (empty($_POST["forgotpassword"]))
     {
     apologize("Please enter email address.");
     }
     
     
     if (empty($_POST["security"]))
     {
     apologize("Please enter your security key.");
     }
     
    $email = $_POST["forgotpassword"];
    if(!(filter_var($email, FILTER_VALIDATE_EMAIL)))
    {
     apologize("Please enter a valid email such as example@domain.com");
    }
     //check if email and securitykey exist in users table
     
    $check= query("SELECT id, security FROM users WHERE email = ?", $email);
    if ($check === false)
    {
    apologize("No such user in database");
    }
     
     else
     {
    [b]render("reset.php", ["title" => "Enter new Password", "check" => $check]); [/b] ///[i]this doesnt work and it prints an error that reset.php is an invalid template...[/i]
    }
  }
 
  else  render("pass_form.php", ["title" => "Forgot Password"]);
 
 
?>





and this is what i've currently got for reset.php...

Code: Select all

<?php
 
   
    // configuration
    require("../includes/config.php");

    // if form was submitted
   if(isset($_POST["submit"]))
    {
   
         if (empty($_POST["password"]))
        apologize("Please enter password.");
       
       
        if ($_POST["password"] != $_POST["confirmation"])
        apologize("Passwords do not match!");
       
       
         $result = query("UPDATE users SET hash = ? WHERE id = ?", crypt($_POST["password"], [b]$check[0]["id"]));[/b]   ///////here is where i want to use the value from $check
       
        if($result===false)
        apologize("Could not register. Please retry.");
       
        else
          {
         
          $rows = query("SELECT id FROM users WHERE hash = ?", crypt($_POST["password"]));
          $id = $rows[0]["id"];
         
          // remember that user's now logged in by storing user's ID in session
          $_SESSION["id"]= $rows[0]["id"];

         
        }
       
         // redirect to portfolio
          redirect("register.php");
       }
           
   
    else
    {
        // else render form
        render("register_form.php", ["title" => "Register"]);
    }
   
?>


and this is the template for reset.php called reset_form.php

Code: Select all

<form action="reset.php" method="post">
    <fieldset>

        <div class="control-group">
            <input name="password" placeholder="Enter new password" type="password"/>
        </div>
        <div class="control-group">
            <input name="confirmation" placeholder="Confirm password" type="password"/>
        </div>
        <div class="control-group">
            <button type="submit" class="btn">Reset Password</button>
        </div>
    </fieldset>
</form>
<div>
    or <a href="login.php">log in</a>
</div>

seandisanti
php-forum Fan User
php-forum Fan User
Posts: 838
Joined: Mon Oct 01, 2012 12:32 pm

Re: weird issue PASSWORD RESET!

Postby seandisanti » Thu Feb 28, 2013 1:25 pm

Ah, i hadn't even looked at the code to realize you were going for an MVC approach, sorry. I've not done very much MVC, and what I have done i just used the yii framework. That said, passing values from one php file to another can be done with 1) sessions 2)request values(post or get, not actually $_REQUEST) 3) cookies, or a file to pass values. Rather than list examples of each, you can see videos of each approach in action at http://jream.com/learning/videos/php-basics

jay93
New php-forum User
New php-forum User
Posts: 5
Joined: Wed Feb 27, 2013 9:53 am

Re: weird issue PASSWORD RESET!

Postby jay93 » Tue Mar 05, 2013 9:55 am

thanks for you help mate...i m facing a new issue at present, could you please help??
i'm currently working on a health website, and i wish to create a page on the website that automatically fetches top articles from a website like http://health.yahoo.net and displays them... i've thought about this for really a long time, but i have no idea on what to do and i ve heard of other people doing similar things like getting their website to display top trending youtube videos, etc... so i really wanted to do this...

2.and another question weighing me down right now is... on another webpage in my health website, i wish to create a search box, where users can type their medical queries and it will automatically display results from google and wikipedia (a search box for each)... the issue is i dont want them to be directed to the homepages of google or wikipedia,(which is pretty simple to do) but instead be shown results directly from them... how could i go about this??

seandisanti
php-forum Fan User
php-forum Fan User
Posts: 838
Joined: Mon Oct 01, 2012 12:32 pm

Re: weird issue PASSWORD RESET!

Postby seandisanti » Wed Mar 06, 2013 11:19 am

cUrl is what you're looking for. It is explained and demonstrated with one of Yahoo's apis at http://jream.com/learning/videos/php-ba ... ng-rest-20


Return to “PHP coding => General”

Who is online

Users browsing this forum: Bing [Bot] and 4 guests