Skip to content

Instantly share code, notes, and snippets.

@iampaul83
Created July 26, 2015 02:59
Show Gist options
  • Save iampaul83/3e459831966e8ef8f85c to your computer and use it in GitHub Desktop.
Save iampaul83/3e459831966e8ef8f85c to your computer and use it in GitHub Desktop.
加密密碼
<?php
/**
* Created by iampaul83
* Date: 7/26/15
* Time: 09:16
*/
$db = new PDO("mysql:host=localhost;dbname=password", "root", "root" );
//$username = $_POST["username"];
//$password = $_POST["password"];
$username = "iampaul83";
$password = "12345678";
$sql = "SELECT EXISTS(SELECT 1 FROM user WHERE username=?);";
$q = $db -> prepare($sql);
$q -> execute(array($username));
$exist = $q -> fetchColumn();
if(!$exist) {
die("帳號不存在,去註冊吧");
}
$sql = "SELECT password_hash FROM user WHERE username=?";
$q = $db -> prepare($sql);
$q -> execute(array($username));
$password_hash = $q -> fetchColumn();
if(password_verify($password, $password_hash)) {
echo "登入成功";
}
else {
echo "密碼錯誤";
}
<?php
/**
* Created by iampaul83
* Date: 7/26/15
* Time: 09:16
*/
$db = new PDO("mysql:host=localhost;dbname=password", "root", "root" );
//$username = $_POST["username"];
//$password = $_POST["password"];
$username = "iampaul83";
$password = "12345678";
$sql = "SELECT EXISTS(SELECT 1 FROM user WHERE username=?);";
$q = $db -> prepare($sql);
$q -> execute(array($username));
$exist = $q -> fetchColumn();
if($exist) {
die("帳號已存在,忘記密碼請點我");
}
/**
* 產生加密的密碼
*
* password_hash
* http://php.net/manual/zh/function.password-hash.php
*
* PASSWORD_DEFAULT - Use the bcrypt algorithm (default as of PHP 5.5.0).
*
* Note that this constant is designed to change over time as new and stronger algorithms are added to PHP.
*
* For that reason, the length of the result from using this identifier can change over time.
*
* Therefore, it is recommended to store the result in a database column
* that can expand beyond 60 characters (255 characters would be a good choice).
*/
$password_hash = password_hash($password, PASSWORD_DEFAULT);
$sql = "INSERT INTO user (username, password_hash) VALUES (:username, :password_hash)";
$q = $db -> prepare($sql);
$v = array(
":username" => $username,
":password_hash" => $password_hash
);
$q -> execute($v);
$error = $q -> errorCode();
if($error == "00000") {
echo "$username"."註冊成功<br>";
}
else {
echo "註冊失敗<br>";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment