logo Send us mail:
contact@reliancewisdom.com
WhatsApp or call:
+234 (0)808 881 1560
TOGGLE NAVIGATION
Back to All Forum Posts
How to Create a Login Form with PHP and MySQL
Ishola Wasiu    Jan 1, 2017 at 05:10 PM    1    2782
Please, how can I create a login form with PHP which fetches data from MySQL database for comparison with data inputted by a user. Any help?
Back to All Forum Posts

1 Answer
Ishola Ayinla says...
Jan 1, 2017 at 05:56 PM

In order to identify a user as authorized, we are going to check the database for his combination of username/password, and if a correct combination was entered, we set a session variable. Then, on top of pages we want to protect, we check for the variable. If user is authorized, we show him the protected content, otherwise we direct him to the login form.

Include this sample piece of code on top of your protected pages:

<?php
if ($_SESSION['authorized'] != true)
{
header("Location: login_form.php");
exit;
}
?>

Now create a simple login form (in a file called login_form.php), and let's make it post to login.php file.

<form method="POST" action="
login.php">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" value="Login">
</form>

In the login.php file, include the database connection string again. Now that we connected to the database, let's check if the user entered correct data. Again, we have our data available in the $_POST array.

$select_user =
mysql_query('select * from users where username = "' .
$_POST['username'] . '" and password = "' .
md5($_POST['password'] . '"'));
 
if (mysql_num_rows($select_user) != 0)
{
session_start();
session_register('authorized');
$_SESSION['authorized'] = true;
 
header("Location: protected_content.php");
exit;
}
else
{
header("Location: login_form.php");
exit;
}

What we do is run a query on the database and select a row with the correct username and password, if it exists. Please notice that we must compare the value for the password from the database with the MD5 encrypted value of the password entered by the user. If the query returns a result, we set the "authorized" session variable, and then redirect to the protected content (in our example protected_content.php). If there are no rows with the entered data, we just redirect the user to the login form again.

These are the basics of creating a membership site. Now that you have the basic knowledge, you can experiment with it and add new features, such as a "Forgot password" page to allow the user to retrieve or change his password if he forgets it, or code to protect against SQL injection.


Full Details