· 10 years ago · Jul 17, 2016, 09:54 PM
1<?php
2// Database definition for MySQL server
3define("DB_HOST", "whatever.com");
4define("DB_USER", "user");
5define("DB_PASS", "pass");
6?>
7
8
9<?php
10
11// index.php
12
13// Log In Script
14// Main Page that allow users to log in and create new accounts
15
16require_once('login.class.php');
17
18
19$login = new Login();
20$login->startSession();
21$login->connectToDB();
22$session_id = session_id();
23
24
25// If the user has a cookie set, redirect him to secure page
26if($login->isAuthorized()) {
27 header("Location: securePage.php");
28}
29
30if($_POST['login']){
31
32 // get the data, trim the blank spacesß
33 $username = trim($_POST['username']);
34 $password = trim($_POST['password']);
35
36 //if checked, the value will be 'on'
37 //otherwise, it will be blank
38 $rememberme = $_POST['rememberme'];
39
40 // verify if the username and password are correct
41 // and if rememberme is set to 'on', create a cookie
42
43 if($username && $password){
44
45 // Check the login details and redirect to securePage.php
46 // if the password is not correct, notify the user
47 $login->checkLogin($username, $password, $rememberme, $session_id);
48
49 } else {
50
51 echo("Please enter a username and password");
52
53 }
54}
55if($_POST['create']){
56
57 // create an account
58 // and notify the user the account has been created
59 $username = trim($_POST['username']);
60 $password = trim($_POST['password']);
61 $first_name = trim($_POST['first_name']);
62 $last_name = trim($_POST['last_name']);
63 $email = trim($_POST['email']);
64 $login->addUser($username, $password, $first_name, $last_name, $email);
65
66
67}
68
69?>
70<html>
71<head>
72<style type="text/css">
73#table {
74 width: 340px;
75 height: 450px;
76 margin: 0 auto;
77 border: 3px solid;
78 padding: 20px;
79}
80</style>
81</head>
82<br/>
83<br/>
84<div id="table">
85<form action="index.php" method="POST">
86Existing Users<hr/>
87Username:
88<input type="text" name="username"></input>
89<br/>
90<br/>
91Password:
92<input type="password" name="password"></input>
93<br/>
94<br/>
95<input type="checkbox" name="rememberme"> Keep Me Logged In</input>
96<br/>
97<br/>
98<input type="submit" name="login" value="Log In"></input>
99</form>
100
101<form action="index.php" method="POST">
102New Users - Sign Up Below<hr/>
103Username:
104<input type="text" name="username"></input>
105<br/>
106<br/>
107Password:
108<input type="password" name="password"></input>
109<br/>
110<br/>
111First Name:
112<input type="text" name="first_name"></input>
113<br/>
114<br/>
115Last Name:
116<input type="text" name="last_name"></input>
117<br/>
118<br/>
119E-Mail:
120<input type="text" name="email"></input>
121<br/>
122<br/>
123<input type="submit" name="create" value="Create A New Account"></input>
124</form>
125
126
127</div>
128</html>
129
130<?php
131
132
133
134// login.class.php
135// This class contains most of the user's functionality
136/*
137 * MySQL Database Information Below
138 * the reason for password being 82 chars is because of the way the salt will be generated and added
139
140
141// user table
142CREATE TABLE `users` (
143 `id` INT NOT NULL AUTO_INCREMENT ,
144 `username` VARCHAR( 64 ) NOT NULL,
145 `password` VARCHAR( 82 ) NOT NULL,
146 `first_name` VARCHAR( 64 ) NOT NULL,
147 `last_name` VARCHAR( 64 ) NOT NULL,
148 `email` VARCHAR ( 64 ) NOT NULL,
149 PRIMARY KEY ( `id` ) ,
150 UNIQUE KEY ( `username`),
151 UNIQUE KEY ( `email` )
152)
153
154// table for storing cookie sessions
155 *
156 You save the session_id in a cookie
157 and once the person visits the website again,
158 the page pulls up a cookie and gets session_id.
159 You then compare current ip and user agent to the ones stored in Session table.
160 After that, you pull up user's data based on user_id from users table.
161
162CREATE TABLE `sessions` (
163`id` INT NOT NULL AUTO_INCREMENT,
164`session_id` VARCHAR(64) NOT NULL,
165`user_ip` VARCHAR(64) NOT NULL ,
166`user_agent` VARCHAR(100) NOT NULL,
167`user_id` VARCHAR(64) NOT NULL,
168PRIMARY KEY ( `id` )
169)
170
171*/
172
173// db defines
174require_once('db_config.php');
175
176
177
178// Salt Length for generateHash function
179define('SALT_LENGTH', 9);
180
181class Login {
182
183 private $username;
184 private $password;
185 private $first_name;
186 private $last_name;
187 private $email;
188 private $session_id;
189
190 public function __construct(){
191 }
192
193 // starts a session
194 public function startSession(){
195 session_start();
196 }
197
198 // Creates a new account based on a new user name and password
199 // username must be unique
200 // password gets md5 (hashed)
201 // It also checks if username already exists
202 public function addUser($username, $password, $first_name, $last_name, $email){
203 $username = $this->clean($username);
204 $password = $this->generateHash($this->clean($password));
205 $first_name = $this->clean($first_name);
206 $last_name = $this->clean($last_name);
207 $email = $this->clean($email);
208
209 // Check if username already exists
210 $query = ("SELECT * FROM users WHERE username = '$username' LIMIT 0,5");
211
212 $result = mysql_query($query) OR die("Cannot perform query!");
213
214 // Check if user name already exists and if it does not exist, create a new account
215
216 if (mysql_num_rows($result) >= 1) {
217 echo "User's name already exists. Please pick another one!";
218 } else {
219
220 // otherwise create an account
221 $query = "INSERT INTO users VALUES('', '" . $username . "', '" . $password . "', '" . $first_name . "'
222 , '" . $last_name . "', '" . $email . "')";
223 $result = mysql_query($query) OR die('Cannot perform query! Make sure you have filled out all the fields!');
224 echo "Your account has been created. You can now log in.";
225 }
226 }
227
228 public function deleteUser($username){
229 $username = $this->clean($username);
230 // Check if username already exists
231 $query = "DELETE FROM users WHERE username = '$username'";
232
233 $result = mysql_query($query) OR die("Cannot perform query!");
234 $this->destroyCookieAndSession();
235 header("Location: index.php");
236
237 }
238
239 // updates user's information
240 public function updateUser($username, $password){
241
242 $username = $this->clean($username);
243 $password = $this->generateHash($this->clean($password));
244
245 $query = "UPDATE users SET password ='$password' WHERE username = '$username'";
246
247 //die();
248 $result = mysql_query($query) OR die("Cannot perform query!");
249 echo "Your changes have been saved.<br/>";
250
251 }
252
253 // Check if the user account and password match the one in the database
254 public function checkLogin($username, $password, $rememberme, $session_id) {
255
256 $this->username = $this->clean($username);
257 $this->password = $this->clean($password);
258 $this->$session_id = $session_id;
259
260 //extract the salt/hash from db and check if the hash/password is correct
261 $query = "SELECT * FROM users WHERE username = '" . $this->username . "' LIMIT 0,1";
262
263 $result = @mysql_query($query) OR die('Cannot perform query!');
264 $row = mysql_fetch_array($result, MYSQL_ASSOC);
265 $dbHash = $row['password'];
266
267
268 // generates hash based on the submitted password and stored salt
269 $this->password = $this->generateHash($this->password, $dbHash);
270
271
272 $query = "SELECT * FROM users WHERE username = '" . $this->username . "' AND
273 password ='" . $this->password . "' LIMIT 0,1";
274
275 $result = mysql_query($query) OR die('Cannot perform query!');
276
277
278 if (mysql_num_rows($result) == 1) {
279
280 //set a cookie if rememberme is set to 'on'
281
282 if($rememberme == "on"){
283 $this->setRememberMe($session_id);
284
285 }
286
287 // user has logged in successfuly, store all his information in this object
288 // before redirecting to securePage.php
289 $this->setFirstName($row['first_name']);
290 $this->setLastName($row['last_name']);
291 $this->setEmail($row['email']);
292
293
294 $this->createSession();
295 header("Location: securePage.php");
296 exit();
297
298 } else {
299
300 echo "Incorrect username or/and password.";
301 }
302
303 // frees the memory used by query
304 mysql_free_result($result);
305 }
306
307 private function createSession(){
308
309
310 // save state of this object before passing
311 // php automatically serializes the object
312 // and will automatically unserialize it
313
314 $_SESSION['usrData'] = $this;
315
316 }
317
318 // sets the cookie
319 // which allows the user to be logged into automatically
320 private function setRememberMe($session_id){
321
322 // check if the user id exists in the session db, if it does, delete that row
323
324 $query = "SELECT * FROM sessions WHERE user_id = '" . $this->getUsername() . "' LIMIT 0,5";
325 $result = mysql_query($query) OR die("Cannot perform query!");
326
327 if (mysql_num_rows($result) >= 1) {
328 $query = "DELETE FROM sessions WHERE user_id = '" . $this->getUsername() . "'";
329 $result = mysql_query($query) OR die("Cannot perform query!");
330 }
331
332 // insert the user's information into a session table
333 $query = "INSERT INTO sessions (session_id, user_ip, user_agent, user_id)
334 VALUES('" . $session_id . "', '" . $_SERVER['REMOTE_ADDR'] . "', '" .
335 $_SERVER['HTTP_USER_AGENT'] . "', '" . $this->getUsername() . "')";
336 $result = mysql_query($query) OR die('Cannot perform query!!');
337
338 // create a cookie with session_id
339 setcookie("autologin", $session_id, time() + 60*60*24*365, "/");
340
341 }
342
343 // check if the user has access to the page
344 public function isAuthorized() {
345
346 // check the session access
347 if(isset($_COOKIE['autologin']) ) {
348
349 // check if user information matches up
350 // we do that by checking user agent and user ip information
351 $session_id = $_COOKIE['autologin'];
352 $user_ip = $_SERVER['REMOTE_ADDR'];
353 $user_agent = $_SERVER['HTTP_USER_AGENT'];
354
355 $query = "SELECT * FROM sessions WHERE session_id = '" . $session_id . "'";
356
357 $result = mysql_query($query) OR die('Cannot perform query!');
358
359 // query the results only once since there's supposed to be only
360 // one record for each session_id
361 $row = mysql_fetch_assoc($result);
362
363 if ( $row["user_ip"] == $user_ip && $row["user_agent"] == $user_agent)
364 {
365 // if everything matches, create a new Login object based on user ID
366
367 // Check if username already exists
368 $query2 = "SELECT * FROM users WHERE username = '" . $row["user_id"] . "' LIMIT 0,5";
369 $result2 = mysql_query($query2) OR die("Cannot perform query!");
370 while ( $row2 = mysql_fetch_assoc($result2) ){
371 $this->username = $row2['username'];
372 $this->first_name = $row2['first_name'];
373 $this->last_name = $row2['last_name'];
374 $this->password = $row2['password'];
375 $this->email = $row2['email'];
376 $this->session_id = $session_id;
377 }
378
379 $_SESSION['usrData'] = $this;
380 return true;
381
382 } else {
383 // Information does not match
384 return false;
385 }
386
387 } else {
388 // if cookie is not set.
389 return false;
390 }
391
392 }
393
394 // private function that allows connection to the database
395 public function connectToDB() {
396 @mysql_connect(DB_HOST, DB_USER, DB_PASS) OR die("Cannot connect to MySQL server!");
397 mysql_select_db("dig_login") OR die("Cannot select database!");
398 }
399
400
401 // Returns the username of a user
402 public function getUsername() {
403 return $this->username;
404 }
405
406 // Returns the plain text password of a user
407 public function getPassword() {
408 return $this->password;
409 }
410 // Returns first name
411 public function getFirstName() {
412 return $this->first_name;
413 }
414 // Returns last name
415 public function getLastName() {
416 return $this->last_name;
417 }
418 public function getEmail() {
419 return $this->email;
420 }
421 //gets session
422 public function getSessionID(){
423 return $this->session;
424 }
425
426
427 // sets first name
428 public function setFirstName($firstName) {
429 $this->first_name = $firstName;
430 }
431 // sets last name
432 public function setLastName($lastName) {
433 $this->last_name = $lastName;
434 }
435 // sets email
436 public function setEmail($email) {
437 $this->email = $email;
438 }
439
440
441 // Escape bad input, sql injections, etc
442 private function clean($input) {
443 return mysql_real_escape_string($input);
444 }
445
446 // Kill the cookie
447 public function destroyCookieAndSession(){
448 setcookie('autologin', '', time()-42000, '/');
449 session_unset();
450 session_destroy();
451
452 }
453 // This is a function that does the hashing
454 // we are going to use sha256 as hashing algorithm
455 // If $salt is not passed, it creates a new salt
456 // otherwise it extracts the salt from db
457 public function generateHash($password, $salt = null){
458
459 if ($salt === null)
460 {
461 $salt = substr(md5(uniqid(rand(), true)), 0, SALT_LENGTH);
462 }
463 else
464 {
465 $salt = substr($salt, 0, SALT_LENGTH);
466
467 }
468
469
470 return $salt . hash('sha256', $salt . $password);
471
472 }
473
474}
475?>
476
477<?php
478// securePage.php
479// if the user has successfully logged in, this page will be shown.
480
481// The form is generated by SESSION variables
482
483require_once('login.class.php');
484session_start();
485
486// if session usr data does not exist, redirect to login page
487if(!$_SESSION['usrData']){
488 header("Location: index.php");
489}
490
491$login = $_SESSION['usrData'];
492
493// re-establish DB connection since Object's DB connection is not persistent
494// once the object is passed through the session
495$login->connectToDB();
496
497echo "<br/>";
498echo "Hello " . $login->getFirstName() . " " . $login->getLastName();
499echo "<br/><br/>";
500
501
502
503if( $_POST['save'] ){
504
505 $login->updateUser(trim($_POST['username']), trim($_POST['password']));
506
507
508}
509if($_POST['delete']){
510
511 $login->deleteUser(trim($_POST['username']));
512
513}
514
515// Logs out the user
516if(isset($_GET['logout']) == "true"){
517 $login->destroyCookieAndSession();
518 header("Location: index.php");
519}
520
521?>
522<br/><br/>
523<form action="securePage.php" method="post">
524<hr/>
525Username: <?php echo $login->getUserName(); ?>
526<input type="hidden" name="username" value="<?php echo $login->getUserName(); ?>"></input>
527<br/>
528<br/>
529Password:
530<input type="password" name="password"></input>
531<br/>
532<br/>
533<br/>
534<input type="submit" name="save" value="Save Changes"></input>
535<input type="submit" name="delete" value="Delete Account"></input>
536</form>
537<hr/>
538<br/>
539<br/>
540<a href="./securePage.php?logout=true">Log Out</a>
541
542// Logs out the user
543if(isset($_GET['logout']) == "true"){
544 $login->destroyCookieAndSession();
545 header("Location: index.php");
546}
547
548// Logs out the user
549if(isset($_GET['logout']) == "true"){
550 $login->destroyCookieAndSession();
551 header("Location: index.php");
552 exit(); // or something like this - maybe return/die?
553}
554
555$result = mysql_query($query)
556 OR die('Cannot perform query! Make sure you have filled out all the fields!');
557
558$query2 = "SELECT * FROM users WHERE username = '" . $row["user_id"] . "' LIMIT 0,5";
559$result2 = mysql_query($query2) OR die("Cannot perform query!");
560while ( $row2 = mysql_fetch_assoc($result2) ){ ... }
561
562// get the data, trim the blank spaces
563$username = trim($_POST['username']);
564
565if($_POST['create']){
566 // create an account
567 // and notify the user the account has been created
568 $username = trim($_POST['username']);
569 $password = trim($_POST['password']);
570
571// Checks user login via information in autologin cookie.
572public function isAuthorized() {
573 if (!isset($_COOKIE['autologin'])) {
574 return false;
575 }
576
577 $session_id = $_COOKIE['autologin'];
578 $query = "SELECT * FROM sessions WHERE session_id = '" . $session_id . "'";
579 $result = mysql_query($query) OR die('Cannot perform query!');
580 $user_by_session = mysql_fetch_assoc($result);
581
582 $user_ip = $_SERVER['REMOTE_ADDR'];
583 $user_agent = $_SERVER['HTTP_USER_AGENT'];
584 if (($user_by_session["user_ip"] != $user_ip) || ($user_by_session["user_agent"] != $user_agent)) {
585 return false;
586 }
587
588 $query = "SELECT * FROM users WHERE username = '" . $user_by_session["user_id"] . "' LIMIT 0,5";
589 $user_entries = mysql_query($query) OR die("Cannot perform query!");
590 while ($row = mysql_fetch_assoc($user_entries)) {
591 $this->username = $row['username'];
592 $this->first_name = $row['first_name'];
593 $this->last_name = $row['last_name'];
594 $this->password = $row['password'];
595 $this->email = $row['email'];
596 $this->session_id = $session_id;
597 }
598
599 $_SESSION['usrData'] = $this;
600 return true;
601}