I remember a time when I used to have a hard time finding a simple, yet effective PHP Login Script (not too long ago!). Sure, I found many scripts with the help of Google, but many of them had errors or weren’t shielded against SQL Injections. Today, I am going to guide you through the steps of creating your own login script — explaining how things work while also providing a basic login script.
Requirements
- PHP version 4.3 or later (I am using PHP 5.3)
- mySQL version 4.1.2 or later (I am using mySQL 5.x)
- A robust web server to execute the script from a browser.
Tutorial
- Create the Database: You will need to create a database and table for the login script to function. In this tutorial, we will assume the database name to be “login_test” and the table name to be “users.” The users table will contain a list of usernames and passwords allowed to connect via the login script. The table should have a unique ID as the primary field, as well a username and password field.
- Create the Login Page: It’ll be an HTML file containing a form with two input fields (username, password) and a submit button.
- Create the PHP Script: You will now need to write the code to be computed and executed by PHP. Of course, I’ve already done this for you, but I am going to explain each piece of code to help you get a grip on what the script does.
Description
- Lines 1 – 5: Define DB_HOST, DB_USER, DB_PASS, and DB_NAME to connect to mySQL Server.
- Line 7: Login Function to verify login credentials.
- Lines 9 – 20: If the $username or $password field are empty, the function will return false, outputting a login error.
- Lines 21 – 22: Escapes special characters in a string for use in an SQL statement to prevent SQL Injections.
- Lines 23 – 24: Create an MD5 Hash of the $password variable and remove any non-alphanumeric characters from the $username.
- Lines 26 – 27: Connect to mySQL Server and select database.
- Lines 29 – 31: Query a match for $username and $password combination.
- Lines 32 – 40: If $result = 1, store $_SESSION[]; else, the function will return false and output a login error for “Invalid Username or Password!”
- Lines 49 – 61: If $_GET['do'] = login or login.php?do=login, then the login function will be executed with values submitted to the login form. It’ll also output login errors and/or redirect you to the login form.
Login.php
<?php
define("DB_HOST", "localhost"); //database host (usually localhost)
define("DB_USER", "username"); //database user to connect to mysql
define("DB_PASS", "password"); //database pass to connect to user
define("DB_NAME", "login_script"); //name of database to be used
function login($username,$password) {
global $error;
if (empty($username) || empty($password)) {
if (empty($username) && empty($password)) {
$error['login'] = "Username and Password cannot be left blank!";
return false;
} elseif (empty($username)) {
$error['login'] = "Username cannot be left blank!";
return false;
} else {
$error['login'] = "Password cannot be left blank!";
return false;
}
}
$username = mysql_real_escape_string($username); //prevents sql injection
$password = mysql_real_escape_string($password); //prevents sql injection
$password = md5($password); //encrypt password using md5 hash
$username2 = preg_replace("/[^a-zA-Z0-9]/", "", $username); //replace non alphanumeric characters
if ($username2 == $username) {
$mysql = mysql_connect(DB_HOST,DB_USER,DB_PASS); //connect to mysql
mysql_select_db(DB_NAME, $mysql); //select the database
if ($mysql) {
$query = mysql_query("SELECT * FROM users WHERE username='$username' AND password='$password'");
$result = mysql_num_rows($query);
mysql_close($mysql);
if ($result == 1) {
session_start();
$_SESSION['loginsys'] = $username . ":" . rand(1,1000);
$_SESSION['loginsys_user'] = $username;
$_SESSION['loginsys_pass'] = $password;
return true;
} else {
$error['login'] = "Invalid Username or Password!";
}
} else {
$error['login'] = "Trouble Connecting to mySQL Server.";
}
} else {
$error['login'] = "Alphanumeric Characters Allowed Only! [Username]";
}
return false;
}
if (isset($_GET['do'])) {
if ($_GET['do'] == "login") {
if (login($_POST['username'],$_POST['password']) && empty($error['login'])) {
header("Location: index.php");
} else {
echo $error['login'];
}
} else {
header("Location: login.php");
}
} else {
include("login.html"); //load html login page
} ?>
Login.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head profile="http://gmpg.org/xfn/11"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Login Form</title> </head> <body> <form name="login" action="login.php?do=login" method="POST"> <input type="text" name="username" value="" /> <input type="password" name="password" value="" /> <input type="submit" name="Login" value="Login" /> </form> </body> </html>
Index.php
<?php
session_start();
if (isset($_SESSION['loginsys'])) {
echo "Success. LoginSys Session = " . $_SESSION['loginsys'];
} else {
header("Location: login.php");
}
?>