#PHP Login
A simple object-oriented PHP login script
Uses the PHP 5.5 secure hashing API, which uses the bcrypt algorithm and an automatically generated salt.
##Requirements
- PHP 5.3.7+
- MySQL 5.5+
- PDO enabled
- MySQL database with a users table as defined below (database name and other constants are defined in
config/db.php
)
##Creating the database
Create the following table in the database defined in config/db.php
:
CREATE TABLE
`users
` (
`user_id`
int(255) NOT NULL AUTO_INCREMENT,
`user_name`
varchar(64) NOT NULL,
`user_fname`
varchar(64) NOT NULL,
`user_lname`
varchar(64) NOT NULL,
`user_pass`
varchar(255) NOT NULL,
PRIMARY KEY (
`user_id`
),
UNIQUE KEY
`user_name`
(
`user_name`
)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
##Directory Structure
/
/classes
user.php -- handles user registration/login/logout
/config
db.php -- defines db constants and opens connection
/css
style.css -- basic styling
/libraries
password.php -- password compatibility library
/views
loggedin.php -- displayed upon user login
login.php -- login form
register.php -- registration form
index.php
init.php -- includes configuration settings
register.php -- user registration page
##Use Cases
The User class (classes/user.php
) handles four general scenarios:
- User with an active session on the server returns to the website
- User attempts to log in
- User attempts to register a new account
- User logs out
It first looks for an existing session and then looks at posted data to determine if a user attempted to register/login/logout.
##Usage
###1. Include init.php
at the top of each page:
require_once("init.php");
init.php
does the following:
- starts (or resumes) a session
- defines database constants
- opens a new connection to the database
- checks the php version and includes the password compatibility library if necessary or stops the script's execution if PHP < 5.3.7
- any other configuration settings should go here
###2. Instantiate a User
object
Create a new User
object, passing it an instance of a PDO database connection:
$user1 = new User($db);
###3. Submit a form to register/login/logout
The action taken will depend on the name of the input[type=submit]
button:
To register:
<input type="submit" name="register" value="Register">
To login:
<input type="submit" name="login" value="Login">
To logout:
<input type="submit" name="logout" value="Logout">