Instead of using SHA family methods, you can use the crypt()
function to salt it for you.
Here is an example script (save and login) using PDO.
Save password in DB
<?php
// Set the password
$password = 'mypassword';
// Get the hash, letting the salt be automatically generated
$hash = crypt($password);
echo $hash; // for testing purposes only
$mysql_username = 'username'; // for DB
$mysql_password = 'password'; // for DB
$dbh = new PDO('mysql:host=localhost;dbname=database_name', $mysql_username, $mysql_password);
$stmt = $dbh->prepare("INSERT INTO table_name (name,pass) VALUES (:name,:pass)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':pass', $pass);
// insert rows
// $name = $_POST['name'];
// $name = $_POST['pass'];
$name = "username";
$pass = $hash;
$stmt->execute();
Login script
<?php
$mysql_username = 'username'; // for DB
$mysql_password = 'password'; // for DB
$dbh = new PDO('mysql:host=localhost;dbname=database_name', $mysql_username, $mysql_password);
/*
$username = $_POST['username'];
$password = $_POST['password'];
*/
$username = "username";
$password = "mypassword";
$sql = "SELECT * FROM table_name WHERE name=:username";
$statement = $dbh->prepare($sql);
$statement->bindValue(':username',$username,PDO::PARAM_STR);
if($statement->execute())
{
if($statement->rowCount() == 1)
{
$row = $statement->fetch(PDO::FETCH_ASSOC);
if (crypt($password, $row['pass']) === $row['pass'])
{
$username = $row['name'];
$email = $row['email'];
echo "Stage 1";
echo "<hr noshade size=\"1\">";
echo "Hello " .$username;
exit;
}
else
{
// include "error_login.php";
echo "Stage 2 - ERROR";
}
}
else
{
// include "error_login.php";
echo "Stage 3 error";
}
}