Saturday 15 March 2014

mysql - Php 5.5 hash API and hashing plain text passwords already in a database -



mysql - Php 5.5 hash API and hashing plain text passwords already in a database -

i found solution problem referenced below may help people using php pdo. tested , works i'm not sure cleanest code or best. improvements welcome.

here original problem reference:

i want hash passwords in mysql database. can hash new passwords using php 5.5 hashing api want know if there way take old plain text passwords , convert them bcrypt hashes. thinking of copying passwords new row called 'hash' and, after checking copied correctly, convert them hashes. not sure how re-create password row , rename on same table, or how hash of these efficiently, though.

any insight appreciated.

here solution:

<? // important: phone call script 1 time or double hash , passwords input users won't work anymore // configuration file require("configsecuresavedgames.php"); // connect server $dbh = new pdo("mysql:host=$host;dbname=$dbname;charset=utf8" , $user, $pass); $dbh->setattribute(pdo::attr_errmode, pdo::errmode_exception); $dbh->setattribute(pdo::attr_emulate_prepares, false); /////////////////////////////////////////////////////// // upload new score /////////////////////////////////////////////////////// // set variable $x 1 start @ id 1 , update each row in loop, adding 1 $x variable 1 time done $x = 1; // note: alter statement below number larger match number of users in database while($x <= 100) { // select hash each row... $stmt = $dbh->prepare("select hash $tname id = $x"); $stmt->execute(); // set resulting array associative $result = $stmt->setfetchmode(pdo::fetch_assoc); // set $hash variable hash (from database) respective row while($row = $stmt->fetch(pdo::fetch_assoc)) { echo $row['hash']; $hash = $row ['hash']; } // update hash row new hash info (note: prior running script create sure you've copied plain text passwords hash row in database. $newhash = password_hash($hash, password_default); $sql = "update securesavegames set hash = '$newhash' id = $x"; // prepare statement $stm = $dbh->prepare($sql); // execute query $stm->execute(); // echo message update succeeded echo $stm->rowcount() . " records updated successfully"; // add together $x hash next 'id' updated, loop continue. $x++; } $dbh = null; ?>

if passwords in plain text, pass them through hash , you'll set.

there's not easy way have 1 query update, because password_hash php function. have fetch values , loop through them. prepared statements help lot this.

$sql = 'select record_id, password table'; $res = $mysqli->query($sql); $sql = 'update table set password = ? record_id = ?'; $prep = $mysqli->prepare($sql); $prep->bind_param('si', $pass, $record); while($row = $res->fetch_assoc()) { $pass = password_hash($row['password']); $record = $row['record_id']; $prep->execute(); }

php mysql sql hash passwords

No comments:

Post a Comment