需要帮助在php中将数组转换为字符串

时间:2015-06-06 19:56:35

标签: php arrays

我正在使用Openwall的PasswordHash.php来哈希密码。方法CheckPassword($ password,$ stored_hash)应该将用户输入的密码与数据库中的哈希密码进行比较。此方法仅接受参数作为字符串。我很难将数组转换为字符串。我从数据库中获取存储的哈希数组并将其破坏。由于某种原因,Checkpassword方法仍然返回false。有人可以帮我解决这个问题吗?

Login.php代码:

<?php 
require 'PasswordHash.php';
// Base-2 logarithm of the iteration count used for password stretching
$hash_cost_log2 = 8;
// Do we require the hashes to be portable to older systems (less secure)?
$hash_portable = FALSE;

$hasher = new PasswordHash($hash_cost_log2, $hash_portable);


$user = $_POST['user'];
$pass = $_POST['pass'];

include ('config.php');

function fail($pub, $pvt = '') {
$msg = $pub;
if ($pvt !== '')
    $msg .= ": $pvt";
exit("An error occurred ($msg).\n");
 }


$db = new mysqli($db_host, $db_user, $db_pass, $db_name, $db_port);
if (mysqli_connect_errno())
fail('MySQL connect', mysqli_connect_error());

$sql = "SELECT pass FROM users WHERE user = '$user'";
$result = $db->query($sql);

if ($result->num_rows == 1){
$stored_hash = mysqli_fetch_array($result);

$stored_hash_ = implode("", $stored_hash);

$check  = $hasher->CheckPassword($pass, $stored_hash_);

if($check) {
    echo "Correct";
} else {
    echo "Wrong pw";
}

} else {

    echo "Error";
}

$db->close();

?>

PasswordHash.php - https://github.com/alexdunae/simplelogin-secure/blob/master/phpass-0.1/PasswordHash.phphttp://www.openwall.com/phpass/

1 个答案:

答案 0 :(得分:0)

如果您执行print_r($stored_hash_);,目前它将返回与此类似的内容:

<pre>
Array [
    ['password_field_name_here'] => 'userpassword123'
]
</pre>

通过循环遍历数组来解决此问题:

if ($result->num_rows == 1){

while ($row = $result->fetch_assoc()) {
    $stored_hash = $row['password_field_name_here'];
}

$stored_hash_ = implode("", $stored_hash);

$check  = $hasher->CheckPassword($pass, $stored_hash_);

if($check) {
    echo "Correct";
} else {
    echo "Wrong pw";
}

例如,$stored_hash_将是; 'userpassword123'