· 9 years ago · Aug 19, 2017, 07:52 AM
1<?php
2
3// First we execute our common code to connection to the database and start the session
4require("common.php");
5
6// This if statement checks to determine whether the registration form has been submitted
7// If it has, then the registration code is run, otherwise the form is displayed
8if(!empty($_POST))
9{
10 // Ensure that the user has entered a non-empty username
11 if(empty($_POST['username']))
12 {
13 // Note that die() is generally a terrible way of handling user errors
14 // like this. It is much better to display the error with the form
15 // and allow the user to correct their mistake. However, that is an
16 // exercise for you to implement yourself.
17 $username_error = "Please enter a username";
18 }
19
20 // Ensure that the user has entered a non-empty password
21 if(empty($_POST['password']))
22 {
23 $password_error = "Please enter a password";
24 }
25
26 // Make sure the user entered a valid E-Mail address
27 // filter_var is a useful PHP function for validating form input, see:
28 // http://us.php.net/manual/en/function.filter-var.php
29 // http://us.php.net/manual/en/filter.filters.php
30 if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
31 {
32 $invalid_email = "Invalid email";
33 }
34
35 // We will use this SQL query to see whether the username entered by the
36 // user is already in use. A SELECT query is used to retrieve data from the database.
37 // :username is a special token, we will substitute a real value in its place when
38 // we execute the query.
39 $query = "
40 SELECT
41 1
42 FROM users
43 WHERE
44 username = :username
45 ";
46
47 // This contains the definitions for any special tokens that we place in
48 // our SQL query. In this case, we are defining a value for the token
49 // :username. It is possible to insert $_POST['username'] directly into
50 // your $query string; however doing so is very insecure and opens your
51 // code up to SQL injection exploits. Using tokens prevents this.
52 // For more information on SQL injections, see Wikipedia:
53 // http://en.wikipedia.org/wiki/SQL_Injection
54 $query_params = array(
55 ':username' => $_POST['username']
56 );
57
58 try
59 {
60 // These two statements run the query against your database table.
61 $stmt = $db->prepare($query);
62 $result = $stmt->execute($query_params);
63 }
64 catch(PDOException $ex)
65 {
66 // Note: On a production website, you should not output $ex->getMessage().
67 // It may provide an attacker with helpful information about your code.
68 die("Failed to run query: " . $ex->getMessage());
69 }
70
71 // The fetch() method returns an array representing the "next" row from
72 // the selected results, or false if there are no more rows to fetch.
73 $row = $stmt->fetch();
74
75 // If a row was returned, then we know a matching username was found in
76 // the database already and we should not allow the user to continue.
77 if($row)
78 {
79 $username_exist = "This username already exists!";
80 }
81
82 // Now we perform the same type of check for the email address, in order
83 // to ensure that it is unique.
84 $query = "
85 SELECT
86 1
87 FROM users
88 WHERE
89 email = :email
90 ";
91
92 $query_params = array(
93 ':email' => $_POST['email']
94 );
95
96 try
97 {
98 $stmt = $db->prepare($query);
99 $result = $stmt->execute($query_params);
100 }
101 catch(PDOException $ex)
102 {
103 die("Failed to run query: " . $ex->getMessage());
104 }
105
106 $row = $stmt->fetch();
107
108 if($row)
109 {
110 $email_registered = "This email is already registered!";
111 }
112
113 // An INSERT query is used to add new rows to a database table.
114 // Again, we are using special tokens (technically called parameters) to
115 // protect against SQL injection attacks.
116 $query = "
117 INSERT INTO users (
118 username,
119 password,
120 salt,
121 email
122 ) VALUES (
123 :username,
124 :password,
125 :salt,
126 :email
127 )
128 ";
129
130 // A salt is randomly generated here to protect again brute force attacks
131 // and rainbow table attacks. The following statement generates a hex
132 // representation of an 8 byte salt. Representing this in hex provides
133 // no additional security, but makes it easier for humans to read.
134 // For more information:
135 // http://en.wikipedia.org/wiki/Salt_%28cryptography%29
136 // http://en.wikipedia.org/wiki/Brute-force_attack
137 // http://en.wikipedia.org/wiki/Rainbow_table
138 $salt = dechex(mt_rand(0, 2147483647)) . dechex(mt_rand(0, 2147483647));
139
140 // This hashes the password with the salt so that it can be stored securely
141 // in your database. The output of this next statement is a 64 byte hex
142 // string representing the 32 byte sha256 hash of the password. The original
143 // password cannot be recovered from the hash. For more information:
144 // http://en.wikipedia.org/wiki/Cryptographic_hash_function
145 $password = hash('sha256', $_POST['password'] . $salt);
146
147 // Next we hash the hash value 65536 more times. The purpose of this is to
148 // protect against brute force attacks. Now an attacker must compute the hash 65537
149 // times for each guess they make against a password, whereas if the password
150 // were hashed only once the attacker would have been able to make 65537 different
151 // guesses in the same amount of time instead of only one.
152 for($round = 0; $round < 65536; $round++)
153 {
154 $password = hash('sha256', $password . $salt);
155 }
156
157 // Here we prepare our tokens for insertion into the SQL query. We do not
158 // store the original password; only the hashed version of it. We do store
159 // the salt (in its plaintext form; this is not a security risk).
160 $query_params = array(
161 ':username' => $_POST['username'],
162 ':password' => $password,
163 ':salt' => $salt,
164 ':email' => $_POST['email']
165 );
166
167 try
168 {
169 // Execute the query to create the user
170 $stmt = $db->prepare($query);
171 $result = $stmt->execute($query_params);
172 }
173 catch(PDOException $ex)
174 {
175 // Note: On a production website, you should not output $ex->getMessage().
176 // It may provide an attacker with helpful information about your code.
177 die("Failed to run query: " . $ex->getMessage());
178 }
179
180 // This redirects the user back to the login page after they register
181 header("Location: login.php");
182
183 // Calling die or exit after performing a redirect using the header function
184 // is critical. The rest of your PHP script will continue to execute and
185 // will be sent to the user if you do not die or exit.
186 die("Redirecting to login.php");
187}
188?>
189
190$isError = false;
191if(empty($username))
192{
193 $isError = true;
194}
195
196if($isError)
197{
198 // Handle error
199}else{
200 // Execute query
201}
202
203function TestSomething($username)
204{
205 if(empty($username))
206 throw new Exception("No username");
207}
208
209try
210{
211 TestSomething("");
212 // Execute query
213}catch(Exception $ex)
214{
215 // Handle error
216 echo $ex->getMessage(); // Prints no username
217}
218
219$error = false;
220if(empty($_POST['username'])) {
221 $error = "Please enter a username";
222}
223
224if(empty($_POST['password'])) {
225 $error = "Please enter a password";
226}
227
228// .. further validation ..
229
230if(!$error) {
231 // Insert new user
232} else {
233 // Redirect back to form with error message(s) set
234}