· 8 years ago · Feb 20, 2018, 07:33 PM
1<?php
2$config = array(
3 // Database
4 'db_host' => 'localhost',
5 'db_user' => 'root',
6 'db_pass' => '',
7 'db_name' => '',
8
9 // Cookies
10 'salt' => '', // make something random up
11 'expire' => 1209600, // 14 days
12);
13
14/*
15 * END OF CONFIG
16 * ------------------------------------------------
17 */
18
19ob_start();
20session_start();
21
22// User class
23// The class is automaticly populated from the database with column names and values
24// To register a user, pass the $_POST data in an array to User::register()
25// To login an user pass username, password and optionally whether to remember or not into User::login()
26// To attempt to auto-login from cookies use User::auto_login
27// To check whether a user is logged in or not use "if (is_object($user)) { }"
28class User
29{
30 /* Users
31 * --------------------------------------
32 CREATE TABLE IF NOT EXISTS `users` (
33 `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
34 `username` varchar(32) NOT NULL,
35 `email` varchar(32) NOT NULL,
36 `password` varchar(64) NOT NULL,
37 `logins` int(10) unsigned NOT NULL,
38 `last_login` int(10) unsigned NOT NULL,
39 PRIMARY KEY (`id`),
40 UNIQUE KEY `username` (`username`)
41 ) ENGINE=MyISAM DEFAULT CHARSET=utf8 ;
42 */
43 public function __construct($id)
44 {
45 global $dbh;
46
47 $sth = $dbh->prepare("SELECT * FROM users WHERE id = :id");
48 if ($sth->execute(array(':id' => $id)))
49 {
50 $row = $sth->fetch(PDO::FETCH_ASSOC);
51 foreach ($row as $key => $value)
52 {
53 $this->{$key} = $value;
54 }
55 }
56 }
57
58 // Static members
59 public static function getUser($id)
60 {
61 global $dbh;
62
63 if (is_string($id))
64 { // $id is the username or email
65 $sth = $dbh->prepare("SELECT id FROM users WHERE username = :id OR email = :id");
66 if ($sth->execute(array(':id' => $id)))
67 {
68 $row = $sth->fetchColumn();
69 return new User($row);
70 }
71 }
72 return FALSE;
73 }
74
75 public static function registerUser($values)
76 {
77 global $dbh;
78
79 $success = true;
80 $errors = array();
81
82 // Username
83 if (empty($values['username']) || !$this->valid_username($values['username']))
84 {
85 $success = FALSE;
86 $errors[] = "Username already taken";
87 }
88
89 // E-Mail
90 if (empty($values['email']) || !$this->valid_email($values['email']))
91 {
92 $success = FALSE;
93 $errors[] = "E-Mail already taken";
94 }
95
96 // Password
97 if ((empty($values['password']) || empty($values['confirm_password']))
98 || ($values['password'] != $values['confirm_passord'])
99 || !$this->valid_password($values['password']))
100 {
101 $success = FALSE;
102 $errors[] = "Passwords don't match";
103 }
104
105 // Insert
106 if ($success)
107 {
108 $sth = $dbh->prepare("INSERT INTO users (username, email, password) VALUES (:username, :email, :password)");
109 $in = array(
110 ':username' => $config['username'],
111 ':email' => $config['email'],
112 ':password' => sha1($config['password'])
113 );
114 if ($sth->execute($in))
115 {
116 return new User($dbh->lastInsertId());
117 }
118 else
119 {
120 $errors[] = "There was an error inserting your account to the databse";
121 }
122 }
123 return FALSE;
124 }
125
126 public static function login($username, $password, $remember = true)
127 {
128 global $dbh;
129
130 $sth = $dbh->prepare("SELECT id FROM users WHERE username = :username AND password = :password");
131 $sth->execute(array(':username' => $username, ':password' => sha1($password)));
132 if ($sth->rowCount() > 0)
133 {
134 $id = $sth->fetchColumn();
135 cookie_set('user', $id);
136 cookie_set('remember', $remember);
137 $_SESSION['user'] = encode($id);
138 $sth = $dbh->prepare("UPDATE users SET logins = logins + 1, last_login = :time WHERE id = :id");
139 $sth->execute(array(':time' => time(), ':id' => $id));
140 return new User($id);
141 }
142 return FALSE;
143 }
144
145 public static function auto_login()
146 {
147 if (isset($_COOKIE['user'], $_COOKIE['remember']) && cookie_get('remember') == true)
148 {
149 $loggedIn = true;
150 return new User(cookie_get('user'));
151 }
152 elseif (isset($_SESSION['user']))
153 {
154 return new User(decode($_SESSION['user']));
155 }
156 return FALSE;
157 }
158
159 public static function logout()
160 {
161 session_destroy();
162 cookie_destroy();
163 }
164
165 // Helpers
166 private static function valid_username($username)
167 {
168 global $dbh;
169
170 $sth = $dbh->prepare("SELECT COUNT(*) FROM users WHERE username = :username");
171 $sth->execute(array(':username' => $username));
172 $num = $sth->rowCount();
173 return $num == 0 && preg_match("/^[a-z\d_]{5,20}$/i", $username);
174 }
175
176 private static function valid_email($email)
177 {
178 global $dbh;
179
180 $sth = $dbh->prepare("SELECT COUNT(*) FROM users WHERE email = :email");
181 $sth->execute(array(':email' => $email));
182 $num = $sth->rowCount();
183 return $num == 0 && preg_match("/^[^@]*@[^@]*\.[^@]*$/", $email);
184 }
185}
186
187function cookie_set($key, $value)
188{
189 setcookie(
190 $key,
191 encode($value),
192 time()+$config['expire']
193 );
194}
195
196function cookie_get($key)
197{
198 return decode($_COOKIE[$key]);
199}
200
201function cookie_destroy()
202{
203 foreach ($_COOKIE as $k => $v)
204 unset($_COOKIE[$k]);
205}
206
207function encode($value)
208{
209 global $config;
210 return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($config['salt']), $value, MCRYPT_MODE_CBC, md5(md5($config['salt']))));
211}
212
213function decode($value)
214{
215 global $config;
216 return rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($config['salt']), base64_decode($value), MCRYPT_MODE_CBC, md5(md5($config['salt']))), "\0");
217}
218
219try {
220 $dbh = new PDO("mysql:host={$config['db_host']};dbname={$config['db_name']};charset=UTF-8;", $config['db_user'], $config['db_pass']);
221}
222catch (Exception $e) {
223 die("Unable to connect to database");
224}
225
226$user = User::auto_login();