PHP Classes

PHP User Login class: Register, login and recover users in a database

Recommend this page to a friend!
     
  Info   Example   View files Files   Install with Composer Install with Composer   Download Download   Reputation   Support forum   Blog    
Ratings Unique User Downloads Download Rankings
StarStarStarStar 72%Total: 1,253 All time: 3,056 This week: 42Up
Version License PHP version Categories
oz-user 1.2GNU General Publi...5PHP 5, User Management
Description 

Author

This class can register, login and recover users in a database.

It can perform several types of user account records stored in a database. Currently it can:

- Retrieve an account by login name
- Retrieve the list of registered users
- Add a new user record
- Update or delete a user record
- Change the user login name or password
- Check if an account exists with a given login name
- Authenticate a user with a login name and password, and start a session if the password is correct
- Logout the current logged user ending his session
- Recover a user account resetting his password

The class database supports several types of databases using PDO like MySQL, Microsoft SQL server and Sybase.

Picture of Oleg Zorin
  Performance   Level  
Name: Oleg Zorin <contact>
Classes: 3 packages by
Country: Russian Federation Russian Federation
Age: 39
All time rank: 185855 in Russian Federation Russian Federation
Week rank: 178 Up10 in Russian Federation Russian Federation Up
Innovation award
Innovation award
Nominee: 1x

Recommendations

What is the best PHP login class?
Login class with forgot password, register, login

Example

<?php
   
/**
    * OZ\User login demo
    */
   
session_start();
    require_once(
'./../user.class.php');

   
/* make it short */
   
use OZ\User as User;
   
   
/* Mysql access */
   
$sql_driver = 'mysql';
   
$sql_host = 'localhost';
   
$sql_name = 'opensource.my';
   
$sql_user = 'root';
   
$sql_pass = '';
   
User::init($sql_driver, $sql_host, $sql_name, $sql_user, $sql_pass);
   
   
/* check current user */
   
$user = false;
    if(
User::check()) {
       
/* redirect to user account */
       
header('Location: account.php');
        exit();
    }

   
/* default values */
   
$login = '';
   
   
/* login routine */
   
$login_error = array();
    if(isset(
$_POST['enter'])) {
       
$login = !empty($_POST['login']) ? $_POST['login'] : '';
       
$password = !empty($_POST['password']) ? $_POST['password'] : '';
       
       
$error_flag = false;
       
        if(empty(
$login)) {
           
/* login is required */
           
$login_error['login'] = 'Login is required';
           
$error_flag = true;
        }
       
        if(empty(
$password)) {
           
/* password is required */
           
$login_error['password'] = 'Password is required';
           
$error_flag = true;
        }
       
       
/* all checks passed */
       
if(!$error_flag) {
            if(
User::login($login, $password)) {
               
/* redirect to user account */
               
header('Location: account.php');
                exit();
            }
            else {
               
$login_error['general'] = 'Something wrong';
            }
        }
    }
   
?>

<html>
    <head>
        <title>User class demo. Login</title>
        <link rel="stylesheet" href="bootstrap/css/bootstrap.min.css"/>
    </head>
    <body>
        <nav class="navbar navbar-default">
            <div class="container-fluid">
                <div class="navbar-header">
                    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                        <span class="sr-only">Toggle navigation</span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>
                    <a class="navbar-brand" href="#">OZ\User demo</a>
                </div>

                <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
                    <ul class="nav navbar-nav">
                        <li class="active"><a href="login.php">Login <span class="sr-only">(current)</span></a></li>
                        <li><a href="registration.php">Registration</a></li>
                        <li><a href="recover.php">Recover account</a></li>
                    </ul>
                </div>
            </div>
        </nav>
   
        <div class="container">
            <h1>Login</h1>
       
            <div class="row">
                <div class="col-xs-12 col-sm-6 col-md-4 col-sm-offset-3 col-md-offset-4">
                    <form action="" method="post">
                        <div class="form-group">
                            <label for="login">Login</label>
                            <input type="text" class="form-control" name="login" id="login" placeholder="Login" value="<?php echo $login; ?>"/>
                            <?php if(!empty($login_error['login'])) { ?>
<br/>
                                <div class="alert alert-danger" role="alert"><?php echo $login_error['login']; ?></div>
                            <?php } ?>
</div>
                        <div class="form-group">
                            <label for="password">Password</label>
                            <input type="password" class="form-control" name="password" id="password" placeholder="Password" value=""/>
                            <?php if(!empty($login_error['password'])) { ?>
<br/>
                                <div class="alert alert-danger" role="alert"><?php echo $login_error['password']; ?></div>
                            <?php } ?>
</div>
                        <button type="submit" name="enter" class="btn btn-primary">Login</button>
                        <?php if(!empty($login_error['general'])) { ?>
<br/><br/>
                            <div class="alert alert-danger" role="alert"><?php echo $login_error['general']; ?></div>
                        <?php } ?>
</form>
                </div>
            </div>
        </div>
    </body>
</html>


Details

User

Universal class for basic user routine. Class definition for your project purpose is required.

Class provides: - user database routine (select / insert / update / delete) - user account routine (login / logout / recover / check)

Probably the best way is to use the ideas of methods realization in your own class.

PHP Tested: 5.6.19, 7.0.11

CONTENTS

1. CLASS DEFINITION
2. PUBLIC METHODS
	2.1. User::init()
	2.2. User::getByID()
	2.3. User::getByLogin()
	2.4. User::getList()
	2.5. User::add()
	2.6. User::update()
	2.7. User::delete()
	2.8. User::loginUpdate()
	2.9. User::loginExists()
	2.10. User::passwordHash()
	2.11. User::passwordCheck()
	2.12. User::passwordUpdate()
	2.13. User::passwordGet()
	2.14. User::login()
	2.15. User::logout()
	2.16. User::recover()
	2.17. User::check()
	2.18. User::getError()

1. CLASS DEFINITION

Class definition is provided in $_definition variable:

private static $_definition = array(
  'table' => 'users',                         /users table name/
  'id' => 'userID',                           /user identifier field name/
  'login' => 'login',                         /user login field name/
  'pass' => 'password',                       /user password field name/
  'key' => 'session_key',                     /user session key field name/
  'fields' => array('group', 'name', 'mail')  /add your fields here/
);

2. CLASS DEFINITION

2.1. User::init($db_drvr, $db_host, $db_name, $db_user, $db_pass)

Initialization of class. Should be called before other methods.

$db_drvr - database driver.

$db_host - database server.

$db_host - database name.

$db_user - database user.

$db_pass - database password.

2.2. User::getByID($userID)

Get user data (except password) by ID.

To get hash of user password use User::passwordGet() method (see section 2.13).

2.3. User::getByLogin($login)

Get user data (except password) by login.

To get hash of user password use User::passwordGet() method (see section 2.13).

It's good idea to use chache here.

2.4. User::getList()

Get users list.

2.5. User::add($data)

Add new user.

$data - user data array with keys according definition.

Password should be provided as is. Method will create hash and write it into database.

2.6. User::update($userID, $data)

Update user data (except login and password).

$data - user data array with keys according definition. Some data could be skipped.

To update login use User::loginUpdate() method (see section 2.8).

To update password use User::passwordUpdate() method (see section 2.12).

2.7. User::delete($userID)

Delete user by ID.

2.8. User::loginUpdate($userID, $login)

Update user login.

2.9. User::loginExists($login, $userID = 0)

Check if $login exists in database. User with $userID skipped.

2.10. User::passwordHash($pass)

Create user password hash using random seed.

2.11. User::passwordCheck($pass, $hash)

Check user password.

2.12. User::passwordUpdate($userID, $pass)

Update user password. Password should be provided as is. Method will create hash and write it into database.

2.13. User::passwordGet()

Get user password hash from database.

2.14. User::login($login, $pass)

Login user in system.

2.15. User::logout()

Logout user.

2.16. User::recover()

Create new password and update database.

2.17. User::check()

Check current user.

2.18. User::getError()

Return list of latest errors as array.


  Files folder image Files (21)  
File Role Description
Files folder imageexamples (6 files, 1 directory)
Accessible without login Plain text file LICENSE Lic. License
Accessible without login Plain text file README.md Doc. Documentation
Plain text file user.class.php Class User class

  Files folder image Files (21)  /  examples  
File Role Description
Files folder imagebootstrap (3 directories)
  Accessible without login Plain text file account.php Example Account demo
  Accessible without login Plain text file login.php Example Login demo
  Accessible without login Plain text file logout.php Example Logout demo
  Accessible without login Plain text file recover.php Example Recover demo
  Accessible without login Plain text file registration.php Example Registration demo
  Accessible without login Plain text file users.sql Data Test sql user table dump

  Files folder image Files (21)  /  examples  /  bootstrap  
File Role Description
Files folder imagecss (8 files)
Files folder imagefonts (1 file)
Files folder imagejs (3 files)

  Files folder image Files (21)  /  examples  /  bootstrap  /  css  
File Role Description
  Accessible without login Plain text file bootstrap-theme.css Data Bootstrap
  Accessible without login Plain text file bootstrap-theme.css.map Data Bootstrap
  Accessible without login Plain text file bootstrap-theme.min.css Data Bootstrap
  Accessible without login Plain text file bootstrap-theme.min.css.map Data Bootstrap
  Accessible without login Plain text file bootstrap.css Data Bootstrap
  Accessible without login Plain text file bootstrap.css.map Data Bootstrap
  Accessible without login Plain text file bootstrap.min.css Data Bootstrap
  Accessible without login Plain text file bootstrap.min.css.map Data Bootstrap

  Files folder image Files (21)  /  examples  /  bootstrap  /  fonts  
File Role Description
  Accessible without login Plain text file glyphicons-halflings-regular.svg Data Bootstrap

  Files folder image Files (21)  /  examples  /  bootstrap  /  js  
File Role Description
  Accessible without login Plain text file bootstrap.js Data Bootstrap
  Accessible without login Plain text file bootstrap.min.js Data Bootstrap
  Accessible without login Plain text file npm.js Data Bootstrap

The PHP Classes site has supported package installation using the Composer tool since 2013, as you may verify by reading this instructions page.
Install with Composer Install with Composer
 Version Control Unique User Downloads Download Rankings  
 100%
Total:1,253
This week:0
All time:3,056
This week:42Up
User Ratings User Comments (2)
 All time
Utility:91%StarStarStarStarStar
Consistency:87%StarStarStarStarStar
Documentation:79%StarStarStarStar
Examples:100%StarStarStarStarStarStar
Tests:-
Videos:-
Overall:72%StarStarStarStar
Rank:172
 
Nice.
7 years ago (Jesus Maria Villalobos)
75%StarStarStarStar
good
7 years ago (muabshir)
62%StarStarStarStar