如何使用password_hash更改密码?

时间:2016-04-14 05:22:34

标签: php mysqli change-password password-hash

当用户输入密码时,如果他想更改密码,我尝试将这个php代码更改为password_hash,但它永远不会匹配,因为存储在我的数据库中的pssword在注册期间被散列,所以我需要他输入的旧pw与db上的哈希密码匹配,这是无法正常工作的。

我知道我应该使用password_verify但我不知道应该插入此代码的哪一部分?

<?php
  include 'session.php';
  $db = new mysqli('localhost', 'root', '', 'alumni');
  if(isset($_POST['submit'])):
  extract($_POST);


  $user_check=$_SESSION['login_user'];

  $old_pwd=$_POST['old_password'];
  $pwd=$_POST['password'];
  $c_pwd=$_POST['confirm_pwd'];
  if($old_pwd!="" && $pwd!="" && $c_pwd!="") :


  if($pwd == $c_pwd) :
  if($pwd!=$old_pwd) :
    $sql="SELECT * FROM `alumni` WHERE `username`='$user_check' AND `password` ='$old_pwd'";
    $db_check=$db->query($sql);
    $count=mysqli_num_rows($db_check);
  if($count==1) :
    $fetch=$db->query("UPDATE `alumni` SET `password` = '$pwd' WHERE `username`='$user_check'");
    $old_pwd=''; $pwd =''; $c_pwd = '';
    $msg_sucess = "Password successfully updated!";
  else:
    $error = "Old password is incorrect. Please try again.";
  endif;
  else :
    $error = "Old password and new password are the same. Please try again.";
  endif;
  else:
    $error = "New password and confirm password do not match.";
  endif;
  else :
    $error = "Please fill all the fields";
  endif;   
  endif;
?> 

2 个答案:

答案 0 :(得分:1)

我终于有了它的工作!非常感谢你的帮助,尤其是肖恩爵士! :d

我改变了这个:

 $sql="SELECT * FROM `alumni` WHERE `username`='$user_check' AND `password` ='$old_pwd'";
$db_check=$db->query($sql);
$count=mysqli_num_rows($db_check);

if($count==1) :
    $fetch=$db->query("UPDATE `alumni` SET `password` = '$pwd' WHERE `username`='$user_check'");

到此:

 $sql=("SELECT * FROM alumni WHERE username='$user_check'");
 $db_check=$db->query($sql);
 if(password_verify($old_pwd,$db_check->fetch_assoc()['password'])):
$fetch=$db->query("UPDATE `alumni` SET `password` = '$new_pw' WHERE username`='$user_check'");

是的,我添加了一个新变量$ new_pw

$new_pw = password_hash($c_pwd, PASSWORD_DEFAULT);

如果你们认为我是以错误的方式做到了,请随时发表评论。谢谢:))

答案 1 :(得分:0)

试一下

        NSURL * URL =  [[NSURL alloc]initWithString:@"http://domainName/message.php?"];

        NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:URL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
        [request setHTTPMethod:@"GET"];

        NSString *tempEmailId  = (NSString *)[[NSUserDefaults standardUserDefaults] objectForKey:CURRENT_USER_EMAIL_ID_UD_KEY];
        NSString *tempPassword = (NSString *)[[NSUserDefaults standardUserDefaults] objectForKey:CURRENT_USER_PASSWORD_UD_KEY];

        NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", tempEmailId, tempPassword];
       [request setValue:[NSString stringWithFormat:@"Basic %@", AFBase64EncodedStringFromString(basicAuthCredentials)] forHTTPHeaderField: @"Authorization"];
       //NSLog(@"request %@\n",request);
       [[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (data != nil) {
            NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSArray * activityItems = @[responseString];
            dispatch_async(dispatch_get_main_queue(), ^{
                activityViewController = [[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities:activities];
                [activityViewController setValue:@"Today's Recommendations" forKey:@"subject"];
                activityViewController.excludedActivityTypes = @[UIActivityTypePostToFacebook];

[activityViewController setCompletionWithItemsHandler:
                 ^(NSString *activityType, BOOL completed, NSArray *returnedItems, NSError *activityError) {
                     dispatch_async(dispatch_get_main_queue(), ^{
                     NSLog(@"activityType: %@, returnedItems: %@, activityError: %@", activityType, returnedItems, activityError.userInfo);

                     if (completed)
                     {
                         NSLog(@"The Activity: %@ was completed", activityType);
                     }
                    else
                     {
                         NSLog(@"The Activity: %@ was NOT completed", activityType);
                     }
                     });

                 }];

                if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
                    [self presentViewController:activityViewController animated:YES completion:nil];
                }
//if iPad
                else {
                    activityViewController.modalPresentationStyle = UIModalPresentationPopover;

                    // activityViewController.popoverPresentationController.sourceView = sender;

                    activityViewController.popoverPresentationController.sourceView = self.view;

                    if ([sender isKindOfClass:[UIButton class]]) {
                        UIButton *btn = (UIButton *)sender;
                        activityViewController.popoverPresentationController.sourceRect = btn.frame;
                    }

                    [self presentViewController:activityViewController animated:YES completion:nil];
                }
            });
        }
    }] resume];