Search code examples
phpmysqlfunctionmd5crypt

how to crypt passwords and use it in a function?


hello i have problems while using crypt function. i would like to check passwords from a database and an entered one.

the problem i have is that when i will enter a password it even will redirect even in case when it is a totally different password? this is strange to me.

so i use this function:

function salt_crypt($login_password, $rounds = 7) { 
    $salt = ""; 
    $salt_chars = array_merge(range('A','Z'), range('a','z'), range(0,9)); for($i=0; $i < 22; $i++) { 
    $salt .= $salt_chars[array_rand($salt_chars)]; 
    } 
    return crypt($login_password, sprintf('$2a$%02d$', $rounds) . $salt);

i will get the stored password from a function that returns an array:

function ab($a){
    global $db;
    $query = $db->query("SELECT col_a, col_b FROM table WHERE Field= '$a' ");
    $check = $query->fetch_assoc();
    return ($check);
}

and this will be used in this function:

function login($a, $login_password){
    $user_data = user_data($a);
    global $db;
    $uname = sanitize($uname);
    $crypted_password = salt_crypt($login_password);

    if(crypt($user_data['col_b'], $crypted_password) == $crypted_password) { 

        $query = $db->query("SELECT col_a FROM table WHERE Field_a= '$a' AND Field_b = '$crypted_password' ");
        $check = $query->num_rows;
        return ($check == 1) ? true : false;
    }
}

this function wil be called and in case of the returning result header with:

$login = login($a, $login_password);
        if ($login === false){
            $errors[] = "text";
        } else {
            header('Location: page.php');
        }

Solution

  • Not all code paths return a value -> your function will return true, even if the if statement is false. Try it with something like this:

    function login($a, $login_password){
    //All your stuff
    
         if(crypt($user_data['col_b'], $crypted_password) == $crypted_password) { 
             //Your stuff
         }
    
        return false
    }