Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- $config = array(
- // Database
- 'db_host' => 'localhost',
- 'db_user' => 'root',
- 'db_pass' => '',
- 'db_name' => '',
- // Cookies
- 'salt' => '', // make something random up
- 'expire' => 1209600, // 14 days
- );
- /*
- * END OF CONFIG
- * ------------------------------------------------
- */
- ob_start();
- session_start();
- // User class
- // The class is automaticly populated from the database with column names and values
- // To register a user, pass the $_POST data in an array to User::register()
- // To login an user pass username, password and optionally whether to remember or not into User::login()
- // To attempt to auto-login from cookies use User::auto_login
- // To check whether a user is logged in or not use "if (is_object($user)) { }"
- class User
- {
- /* Users
- * --------------------------------------
- CREATE TABLE IF NOT EXISTS `users` (
- `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
- `username` varchar(32) NOT NULL,
- `email` varchar(32) NOT NULL,
- `password` varchar(64) NOT NULL,
- `logins` int(10) unsigned NOT NULL,
- `last_login` int(10) unsigned NOT NULL,
- PRIMARY KEY (`id`),
- UNIQUE KEY `username` (`username`)
- ) ENGINE=MyISAM DEFAULT CHARSET=utf8 ;
- */
- public function __construct($id)
- {
- global $dbh;
- $sth = $dbh->prepare("SELECT * FROM users WHERE id = :id");
- if ($sth->execute(array(':id' => $id)))
- {
- $row = $sth->fetch(PDO::FETCH_ASSOC);
- foreach ($row as $key => $value)
- {
- $this->{$key} = $value;
- }
- }
- }
- // Static members
- public static function getUser($id)
- {
- global $dbh;
- if (is_string($id))
- { // $id is the username or email
- $sth = $dbh->prepare("SELECT id FROM users WHERE username = :id OR email = :id");
- if ($sth->execute(array(':id' => $id)))
- {
- $row = $sth->fetchColumn();
- return new User($row);
- }
- }
- return FALSE;
- }
- public static function registerUser($values)
- {
- global $dbh;
- $success = true;
- $errors = array();
- // Username
- if (empty($values['username']) || !$this->valid_username($values['username']))
- {
- $success = FALSE;
- $errors[] = "Username already taken";
- }
- // E-Mail
- if (empty($values['email']) || !$this->valid_email($values['email']))
- {
- $success = FALSE;
- $errors[] = "E-Mail already taken";
- }
- // Password
- if ((empty($values['password']) || empty($values['confirm_password']))
- || ($values['password'] != $values['confirm_passord'])
- || !$this->valid_password($values['password']))
- {
- $success = FALSE;
- $errors[] = "Passwords don't match";
- }
- // Insert
- if ($success)
- {
- $sth = $dbh->prepare("INSERT INTO users (username, email, password) VALUES (:username, :email, :password)");
- $in = array(
- ':username' => $config['username'],
- ':email' => $config['email'],
- ':password' => sha1($config['password'])
- );
- if ($sth->execute($in))
- {
- return new User($dbh->lastInsertId());
- }
- else
- {
- $errors[] = "There was an error inserting your account to the databse";
- }
- }
- return FALSE;
- }
- public static function login($username, $password, $remember = true)
- {
- global $dbh;
- $sth = $dbh->prepare("SELECT id FROM users WHERE username = :username AND password = :password");
- $sth->execute(array(':username' => $username, ':password' => sha1($password)));
- if ($sth->rowCount() > 0)
- {
- $id = $sth->fetchColumn();
- cookie_set('user', $id);
- cookie_set('remember', $remember);
- $_SESSION['user'] = encode($id);
- $sth = $dbh->prepare("UPDATE users SET logins = logins + 1, last_login = :time WHERE id = :id");
- $sth->execute(array(':time' => time(), ':id' => $id));
- return new User($id);
- }
- return FALSE;
- }
- public static function auto_login()
- {
- if (isset($_COOKIE['user'], $_COOKIE['remember']) && cookie_get('remember') == true)
- {
- $loggedIn = true;
- return new User(cookie_get('user'));
- }
- elseif (isset($_SESSION['user']))
- {
- return new User(decode($_SESSION['user']));
- }
- return FALSE;
- }
- public static function logout()
- {
- session_destroy();
- cookie_destroy();
- }
- // Helpers
- private static function valid_username($username)
- {
- global $dbh;
- $sth = $dbh->prepare("SELECT COUNT(*) FROM users WHERE username = :username");
- $sth->execute(array(':username' => $username));
- $num = $sth->rowCount();
- return $num == 0 && preg_match("/^[a-z\d_]{5,20}$/i", $username);
- }
- private static function valid_email($email)
- {
- global $dbh;
- $sth = $dbh->prepare("SELECT COUNT(*) FROM users WHERE email = :email");
- $sth->execute(array(':email' => $email));
- $num = $sth->rowCount();
- return $num == 0 && preg_match("/^[^@]*@[^@]*\.[^@]*$/", $email);
- }
- }
- function cookie_set($key, $value)
- {
- setcookie(
- $key,
- encode($value),
- time()+$config['expire']
- );
- }
- function cookie_get($key)
- {
- return decode($_COOKIE[$key]);
- }
- function cookie_destroy()
- {
- foreach ($_COOKIE as $k => $v)
- unset($_COOKIE[$k]);
- }
- function encode($value)
- {
- global $config;
- return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($config['salt']), $value, MCRYPT_MODE_CBC, md5(md5($config['salt']))));
- }
- function decode($value)
- {
- global $config;
- return rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($config['salt']), base64_decode($value), MCRYPT_MODE_CBC, md5(md5($config['salt']))), "\0");
- }
- try {
- $dbh = new PDO("mysql:host={$config['db_host']};dbname={$config['db_name']};charset=UTF-8;", $config['db_user'], $config['db_pass']);
- }
- catch (Exception $e) {
- die("Unable to connect to database");
- }
- $user = User::auto_login();
Add Comment
Please, Sign In to add comment