· 8 years ago · Feb 20, 2018, 06:58 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// Do not touch!
15class User
16{
17 /* Users
18 * --------------------------------------
19 CREATE TABLE IF NOT EXISTS `users` (
20 `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
21 `username` varchar(32) NOT NULL,
22 `email` varchar(32) NOT NULL,
23 `password` varchar(64) NOT NULL,
24 `logins` int(10) unsigned NOT NULL,
25 `last_login` int(10) unsigned NOT NULL,
26 PRIMARY KEY (`id`),
27 UNIQUE KEY `username` (`username`)
28 ) ENGINE=MyISAM DEFAULT CHARSET=utf8 ;
29 */
30 public function __construct($id)
31 {
32 global $dbh;
33
34 $sth = $dbh->prepare("SELECT * FROM users WHERE id = :id");
35 $sth->execute(array(':id' => $id));
36 $row = $sth->fetch(PDO::FETCH_ASSOC);
37 foreach ($row as $key => $value)
38 {
39 $this->{$key} = $value;
40 }
41 }
42
43 // Static members
44 public static function getUser($id)
45 {
46 global $dbh;
47
48 if (is_string($id))
49 { // $id is the username or email
50 $row = $dbh->prepare("SELECT id FROM users WHERE username = :id OR email = :id")->execute(array(':id' => $id))->fetchColumn();
51 return new User($row);
52 }
53 else { return FALSE; }
54 }
55
56 public static function registerUser($values)
57 {
58 global $dbh;
59
60 $success = true;
61 $errors = array();
62
63 // Username
64 if (empty($values['username']) || !$this->valid_username($values['username']))
65 {
66 $success = FALSE;
67 $errors[] = "Username already taken";
68 }
69
70 // E-Mail
71 if (empty($values['email']) || !$this->valid_email($values['email']))
72 {
73 $success = FALSE;
74 $errors[] = "E-Mail already taken";
75 }
76
77 if ((empty($values['password']) || empty($values['confirm_password']))
78 || ($values['password'] != $values['confirm_passord'])
79 || !$this->valid_password($values['password']))
80 {
81 $success = FALSE;
82 $errors[] = "Passwords don't match";
83 }
84
85 if ($success)
86 {
87 $sth = $dbh->prepare("INSERT INTO users (username, email, password) VALUES (:username, :email, :password)");
88 $in = array(
89 ':username' => $config['username'],
90 ':email' => $config['email'],
91 ':password' => sha1($config['password'])
92 );
93 if ($sth->execute($in))
94 {
95 return new User($dbh->lastInsertId());
96 }
97 else
98 {
99 $errors[] = "There was an error inserting your account to the databse";
100 }
101 }
102 return FALSE;
103 }
104
105 public static function login($username, $password, $remember = true)
106 {
107 global $dbh;
108
109 $sth = $dbh->prepare("SELECT id FROM users WHERE username = :username AND password = :password")
110 ->execute(array(':username' => $username, ':password' => sha1($password)));
111 if ($sth->rowCount() > 0)
112 {
113 $id = $sth->fetchColumn();
114 cookie_set('user', $id);
115 cookie_set('remember', $remember);
116 $dbh->prepare("UPDATE users SET logins = logins + 1, last_login = :time WHERE id = :id")
117 ->execute(array(':time' => time(), ':id' => $id));
118 return new User($id);
119 }
120 return FALSE;
121 }
122
123 public static function auto_login()
124 {
125 if (isset($_COOKIE['user'], $_COOKIE['remember']) && cookie_get('remember') == true)
126 {
127 return new User(cookie_get('user'));
128 }
129 return FALSE;
130 }
131
132 // Helpers
133 private static function valid_username($username)
134 {
135 global $dbh;
136
137 $num = $dbh->prepare("SELECT COUNT(*) FROM users WHERE username = :username")
138 ->execute(array(':username' => $username))
139 ->rowCount();
140 return $num == 0 && preg_match("/^[a-z\d_]{5,20}$/i", $username);
141 }
142
143 private static function valid_email($email)
144 {
145 global $dbh;
146
147 $num = $dbh->prepare("SELECT COUNT(*) FROM users WHERE email = :email")
148 ->execute(array(':email' => $email))
149 ->rowCount();
150 return $num == 0 && preg_match("/^[^@]*@[^@]*\.[^@]*$/", $email);
151 }
152}
153
154function cookie_set($key, $value)
155{
156 global $config;
157 setcookie(
158 $key,
159 base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($config['salt']), $value, MCRYPT_MODE_CBC, md5(md5($config['salt'])))),
160 time()+$config['expire']
161 );
162}
163
164function cookie_get($key)
165{
166 global $config;
167 return rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($config['salt']), base64_decode($_COOKIE[$key]), MCRYPT_MODE_CBC, md5(md5($config['salt']))), "\0");
168}
169
170try {
171 $dbh = new PDO("mysql:host={$config['db_host']};dbname={$config['db_name']};charset=UTF-8;", $config['db_user'], $config['db_pass']);
172}
173catch (Exception $e) {
174 die("Unable to connect to database");
175}
176
177$user = User::auto_login();
178
179// use if (is_object($user)) to check whether user is logged in or not!