Saturday, January 30, 2016

LOGIN IN PHP: Create a Database Driven Login Form Using PHP and MySQL

In every information system, user authentication is essential to ensure that data are accessed by the right people. Since data is integral in every business, security is integrated in an information system to protect their processed data that are stored in their database.

That's why a username or an email address and a password is required to accessed a certain system. That username/email and password should match an existing username and password in a database.

So I have here a login form for the interface and PHP for the functionality. First is you need to construct your HTML form like the code below:

HTML Code Login

<!DOCTYPE html>
<title>PHP Addict | Login</title>
<form method="post" action="login.php">
<label for="user">Username</label>
<input type="text" class="form-control" id="user" name="user" placeholder="Username" required>
<label for="pass">Password</label>
<input type="password" id="pass" name="pass" placeholder="Password" required>
<button type="submit" name="login">Login</button>
<button type="reset">Clear</button>

Output of HTML Login

PHP Code for login

Copy and save the code below as login.php

$con = mysqli_connect("localhost","root","","dbname");
// Check connection
if (mysqli_connect_errno())
echo "Failed to connect to MySQL: " . mysqli_connect_error();


$user = mysqli_real_escape_string($con,$user_unsafe);
$pass = mysqli_real_escape_string($con,$pass_unsafe);

$query=mysqli_query($con,"select * from student where user='$user' and pass='$pass'")or die(mysqli_error());

if ($counter == 0)
echo "<script type='text/javascript'>alert('Invalid Username or Password!');
elseif ($counter > 0)
echo "<script type='text/javascript'>document.location='home.php'</script>";

Explanation: The first eight (8) lines of code serves as your database connection. The purpose of the $counter is to count the number of returned rows from your table. So if returned rows is equal to zero (0), it will display Invalid Username or Password and will redirect you to index.php. Otherwise,  it will store the student id to SESSION['id'] to be able to access it later and redirect you to home.php.

Reminder: Put  the session_start() at the start of the login page or in any page that will access the value of SESSION['id'].

Thank you for visiting and hope this helps you. Feel free to leave a comment below for any questions. I got some other articles related to php and mysql here in my blog. Watch out for more upcoming tutorials related to blogging and programming. Good day! ^_^

LOGIN IN PHP: Create a Database Driven Login Form Using PHP and MySQL

No comments:

Post a Comment