· 9 years ago · Oct 18, 2016, 02:56 AM
1<?php
2
3include "connect.inc.php";
4
5 //Establish connection to the database
6 try
7 {
8 $pdo = new PDO("mysql:host=$host;dbname=$database", $userMS, $passwordMS);
9 $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
10 $pdo->exec('SET NAMES "utf8"');
11 }
12 catch (PDOException $e)
13 {
14 $error = "Connection to database server connection failed";
15 include 'error.html.php';
16 exit();
17 }
18
19
20 try
21 {
22 $dropQuery = "DROP TABLE IF EXISTS tblPasswords";
23 $pdo->exec($dropQuery);
24 }
25 catch (PDOException $e)
26 {
27 $error = "Dropping tblPasswords";
28 include 'error.html.php';
29 exit();
30 }
31
32 //Try to drop event table. Make event table.
33 try
34 {
35 $createQuery = "CREATE TABLE tblPasswords
36 (
37 userID INT(6) NOT NULL AUTO_INCREMENT,
38 userName VARCHAR (20) NOT NULL,
39 userPassword VARCHAR(15) NOT NULL,
40
41 PRIMARY KEY(userID)
42 )";
43 $pdo->exec($createQuery);
44 }
45 catch (PDOException $e)
46 {
47 $error = "Creating the password table failed";
48 include 'error.html.php';
49 exit();
50 }
51
52 function doInsert($name, $password, $pdo)
53 {
54 //A highter "cost" is more secure but consumes more processing power.
55 $cost = 10;
56
57 //Create a random salt
58 $salt = strtr(base64_encode(mcrypt_create_iv(16, MCRYPT_DEV_URANDOM)), '+', '.');
59
60 //Prefix infromation about the hash so PHP knows how to verify it later.
61 //"$2a$" Means we're using the Blowfish algorithm. The following two digits are the cost parameter.
62 $salt = sprintf("$2a$%02d$", "$cost") . $salt;
63 echo("$salt<br>");
64 //Hash the password with the salt
65 $hash = crypt($password, $salt);
66 echo("$hash<br>");
67
68 $insertQuery = "INSERT INTO tblPasswords (userName, userPassword) VALUES ('$name','$hash')";
69 $pdo->exec($insertQuery);
70 }
71
72doInsert('testOne','testOne',$pdo);
73doInsert('testTwo','testTwo',$pdo);
74
75$selectQuery = "SELECT * FROM tblPasswords";
76$result = $pdo->query($selectQuery);
77
78?>