Må bruke tutorials som er litt mer oppdaterte. session_register og mysql_query er deprecated / utgått på dato.
MD5 er forferdelig utgått på dato, så det får du ikke bruke uansett hvor lite prosjektet måtte være.
Legg dette hashet inn i databasen for brukeren din (passord123).
$2a$15$kNybYK3AX7kkALFf8NjG4.MLCWdDKZNXer.nxRQAM1Cqag5fIeFHq
Slengte med et innloggingsskjema for å gjøre testing enklere (da jeg ikke hadde resten av koden din), skjemaet kan du jo evnt bare fjerne. Merk at session_start(); bør ligge først i index.php
Ser ikke helt grunnen til å lagre passordet i session, men det er nå så.
Linje 19-22
Må oppdateres med riktig data.
Linje 46
username og password må endres til å reflektere kolonnenavnene i databasen din
:username og :password er bare markører, dersom du ønsker å skifte dem må du skifte i arrayet i linje 47 og.
Linje 54-55
username og password må endres til å reflektere kolonnenavnene i databasen din
Kode
<?php
// Turn on error reporting, dev enviroment only!
ini_set('error_reporting', E_ALL);
// Start user session.
session_start();
// This class should be moved into its own file and included in your project. include('class.Bcrypt.php');
class Bcrypt {
private $rounds;
public function __construct($rounds = 12) {
if(CRYPT_BLOWFISH != 1) {
throw new Exception("bcrypt not supported in this installation. See http://php.net/crypt");
}
$this->rounds = $rounds;
}
public function hash($input) {
$hash = crypt($input, $this->getSalt());
if(strlen($hash) > 13)
return $hash;
return false;
}
public function verify($input, $existingHash) {
$hash = crypt($input, $existingHash);
return $hash === $existingHash;
}
private function getSalt() {
$salt = sprintf('$2a$%02d$', $this->rounds);
$bytes = $this->getRandomBytes(16);
$salt .= $this->encodeBytes($bytes);
return $salt;
}
private $randomState;
private function getRandomBytes($count) {
$bytes = '';
if(function_exists('openssl_random_pseudo_bytes') &&
(strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN')) { // OpenSSL slow on Win
$bytes = openssl_random_pseudo_bytes($count);
}
if($bytes === '' && is_readable('/dev/urandom') &&
($hRand = @fopen('/dev/urandom', 'rb')) !== FALSE) {
$bytes = fread($hRand, $count);
fclose($hRand);
}
if(strlen($bytes) < $count) {
$bytes = '';
if($this->randomState === null) {
$this->randomState = microtime();
if(function_exists('getmypid')) {
$this->randomState .= getmypid();
}
}
for($i = 0; $i < $count; $i += 16) {
$this->randomState = md5(microtime() . $this->randomState);
if (PHP_VERSION >= '5') {
$bytes .= md5($this->randomState, true);
} else {
$bytes .= pack('H*', md5($this->randomState));
}
}
$bytes = substr($bytes, 0, $count);
}
return $bytes;
}
private function encodeBytes($input) {
// The following is code from the PHP Password Hashing Framework
$itoa64 = './ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$output = '';
$i = 0;
do {
$c1 = ord($input[$i++]);
$output .= $itoa64[$c1 >> 2];
$c1 = ($c1 & 0x03) << 4;
if ($i >= 16) {
$output .= $itoa64[$c1];
break;
}
$c2 = ord($input[$i++]);
$c1 |= $c2 >> 4;
$output .= $itoa64[$c1];
$c1 = ($c2 & 0x0f) << 2;
$c2 = ord($input[$i++]);
$c1 |= $c2 >> 6;
$output .= $itoa64[$c1];
$output .= $itoa64[$c2 & 0x3f];
} while (1);
return $output;
}
}
// @todo Split config variables and DB functions into config file / classes.
/**
* PDO Query
* @param string $query
* @param array $params ex: array(':field1' => $field1)
* @param string $fetch_method "ASSOC" (default), "BOTH", "BOUND", "CLASS", "CLASSTYPE", "INTO", "LAZY", "NUM", "OBJ"
* @return array
*/
function pdo_query($query = '', $params = array(), $fetch_method = 'ASSOC') {
$db_host='localhost'; // Host name
$db_username='test'; // Mysql username
$db_password='**********'; // Mysql password
$db_name='roccat'; // Database name
if(!isset($dbh)) {
// Connect to DB.
$dbh = new PDO('mysql:host='.$db_host.';dbname='.$db_name, $db_username, $db_password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
try {
$stmt = $dbh->prepare($query);
$result = $stmt->execute($params);
return $stmt->fetchAll(constant('PDO::FETCH_'.strtoupper($fetch_method)));
} catch(PDOException $ex) {
// This should be divided between friendly user errors and server logging.
echo 'An Error occured! '.$ex->getMessage();
}
}
if(isset($_POST['token'], $_SESSION['token-expires'])) {
if($_POST['token'] === $_SESSION['token'] && time() < $_SESSION['token-expires']) {
if(isset($_POST['myusername'], $_POST['mypassword'])){
$query = 'SELECT username, password FROM members WHERE username = :username';
$params = array(':username' => $_POST['myusername'], ':password' => $_POST['mypassword']);
$result = pdo_query($query, $params, 'OBJ');
if($result[0]->username) {
// We have a user! Now let's see if he has supplied the correct password
$bcrypt = new Bcrypt(15);
$hash = $bcrypt->hash($_POST['mypassword']);
if($bcrypt->verify($result[0]->password, $hash)) {
// Passwords match! Set session variable and redirect
$_SESSION['myusername'] = $result[0]->username;
$_SESSION['mypassword'] = $result[0]->password;
header('location:login_success.php');
} else {
// Debug env only. Shouldn't display this to users because it helps with brute forcing.
echo 'Wrong password';
}
} else {
// Debug env only. Shouldn't display this to users because it helps with brute forcing.
echo 'No such user';
}
} else {
'Username or password missing!';
}
} else {
echo 'Token error, please try again';
}
}
// Create (new) form token, CSRF protection.
$token = md5(microtime(TRUE) . rand(0, 100000));
$_SESSION['token'] = $token;
$_SESSION['token-expires'] = time() + 1800;
?>
<form method="POST">
<input type="hidden" name="token" value="<?php echo $token; ?>">
<input type="text" name="myusername"><br />
<input type="password" name="mypassword"><br />
<input type="submit" value="Logg inn">
</form>
Sist endret av norboost; 23. mars 2013 kl. 13:27.