Вы находитесь на странице: 1из 22

5 Easy Steps to Create Simple & Secure PHP Login Script - Free https://codingcyber.

org/simple-login-script-php-and-mysql-64/

Home PHP WordPress Video C

Home → PHP → 5 Steps to Create Simple Secure Login Script in PHP and MySql

5 Steps to Create Simple Secure


Login Script in PHP and MySql
This is a Simple to Advanced Login Script System using PHP and MySQL. In this script, a form
will be displayed with two �elds, username, and password. When the user is submitting with
valid username and password, then he can access authenticated page. Otherwise, users
again have to �ll in the form. This is a continuation from the last article Simple User
Registration Script in PHP and MySql. If you want to follow next article these are the links.

Here you will learn about Simple Login System & also an advanced system. Simple Login
Script System is targetted towards beginners and helps you to learn the script easily.
Advanced Login Script System is more secure than the simple Login Script and it is targetted
towards intermediate, advanced users even beginners also can easily understand it. I’ve also
created video tutorials for both the Login Systems. And also I’ve created a video course, I

1 sur 22 13-02-20 à 22:03


5 Easy Steps to Create Simple & Secure PHP Login Script - Free https://codingcyber.org/simple-login-script-php-and-mysql-64/

highly encourage you to join my course. So that, you will learn more advanced topics in user
login & registration system.

(i). Simple User Login Script in PHP & MySQL


(ii). Advanced User Login, Registration, Forgot(reset) Password in PHP & MySQL

1. Simple User Registration Script in PHP and MySQL


2. Simple Login Script in PHP and MySQL
3. User Login with activation check using PHP and MySQL
4. Send Forgotten Password by mail using PHP and MySQL
5. Check Username Availability With jQuery In PHP And MySql

(i). Steps to create Simple Login


Script in PHP and MySQL
1. First step we will connect to the database.
2. Then we will select the database.
3. We are checking, if the form is submitted or not. In this step we have two logic’s.
What if the form is submitted.
1. If the form is submitted, we are assigning the posted values to variables
and checking the values are existing in the database or not.
2. If the values submitted in the form and the values in the database are
equal, then we will create a session for the user.
3. If the values are not equal then it will display an error message.
4. And then we checks for the session, if the session exists we will great
him with the username, otherwise the form will be displayed.

What if not the form is submitted.


1. When the user comes �rst time, he will be displayed with a simple form.
2. User Name, Password and a submit button.

Below is the Video on Simple User Login

2 sur 22 13-02-20 à 22:03


5 Easy Steps to Create Simple & Secure PHP Login Script - Free https://codingcyber.org/simple-login-script-php-and-mysql-64/

Registration Script in PHP

PHP User Registration & Login System Script

Subscribe on Youtube

Vivek Vengala

1. Create a Database Table


If you are already following from previous article, you should already have database table
created. If you don’t have create the table.

1 CREATE TABLE `user` (


2   `id` int(11) NOT NULL AUTO_INCREMENT,
3   `username` varchar(255) NOT NULL,
4   `email` varchar(255) NOT NULL,
5   `password` varchar(255) NOT NULL,
6   `active` tinyint(1) NOT NULL,
7   PRIMARY KEY (`id`),
8   UNIQUE KEY `username` (`username`)
9 )

2. Creating HTML User Login Form


This is the form, only displayed if message variable in not set.

1       <form class="form-signin" method="POST">


2         <h2 class="form-signin-heading">Please Login</h2>

3 sur 22 13-02-20 à 22:03


5 Easy Steps to Create Simple & Secure PHP Login Script - Free https://codingcyber.org/simple-login-script-php-and-mysql-64/

3         <div class="input-group">
4   <span class="input-group-addon" id="basic-addon1">@</span>
5   <input type="text" name="username" class="form-control" placeholder="Username" required
6 </div>
7         <label for="inputPassword" class="sr-only">Password</label>
8         <input type="password" name="password" id="inputPassword" class="form-control" placeholder
9         <button class="btn btn-lg btn-primary btn-block" type="submit">Login</button>
10         <a class="btn btn-lg btn-primary btn-block" href="register.php">Register</a>
11       </form>

3. Adding styles to Login Form


And the styles for the form, if you have added styles in previous article. Skip this step.

1 <!-- Latest compiled and minified CSS -->


2 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
3
4 <!-- Optional theme -->
5 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min
6
7 <link rel="stylesheet" href="styles.css" >
8
9 <!-- Latest compiled and minified JavaScript -->
10 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

1 body {
2   padding-top: 40px;
3   padding-bottom: 40px;
4   background-color: #eee;
5 }
6
7 .form-signin {
8   max-width: 330px;
9   padding: 15px;
10   margin: 0 auto;
11 }
12 .form-signin .form-signin-heading,
13 .form-signin .checkbox {
14   margin-bottom: 10px;
15 }
16 .form-signin .checkbox {
17   font-weight: normal;
18 }
19 .form-signin .form-control {
20   position: relative;
21   height: auto;
22   -webkit-box-sizing: border-box;
23      -moz-box-sizing: border-box;
24           box-sizing: border-box;
25   padding: 10px;
26   font-size: 16px;
27 }
28 .form-signin .form-control:focus {
29   z-index: 2;
30 }
31 .form-signin input[type="email"] {
32   margin-bottom: -1px;
33   border-bottom-right-radius: 0;
34   border-bottom-left-radius: 0;
35 }

4 sur 22 13-02-20 à 22:03


5 Easy Steps to Create Simple & Secure PHP Login Script - Free https://codingcyber.org/simple-login-script-php-and-mysql-64/

36 .form-signin input[type="password"] {
37   margin-bottom: 10px;
38   border-top-left-radius: 0;
39   border-top-right-radius: 0;
40 }

4. Connect to Database
If you are following from previous user registration article, no need to create this �le. Other
wise create connect.php �le.

1 <?php
2 $connection = mysqli_connect('localhost', 'root', 'Rvm@i[9)0?~=');
3 if (!$connection){
4     die("Database Connection Failed" . mysqli_error($connection));
5 }
6 $select_db = mysqli_select_db($connection, 'test');
7 if (!$select_db){
8     die("Database Selection Failed" . mysqli_error($connection));
9 }

5. PHP Logic for User Login


And this is the PHP code for logging in user

1 <?php  //Start the Session


2 session_start();
3 require('connect.php');
4 //3. If the form is submitted or not.
5 //3.1 If the form is submitted
6 if (isset($_POST['username']) and isset($_POST['password'])){
7 //3.1.1 Assigning posted values to variables.
8 $username = $_POST['username'];
9 $password = $_POST['password'];
10 //3.1.2 Checking the values are existing in the database or not
11 $query = "SELECT * FROM `user` WHERE username='$username' and password='$password'";
12
13 $result = mysqli_query($connection, $query) or die(mysqli_error($connection));
14 $count = mysqli_num_rows($result);
15 //3.1.2 If the posted values are equal to the database values, then session will be created for the
16 if ($count == 1){
17 $_SESSION['username'] = $username;
18 }else{
19 //3.1.3 If the login credentials doesn't match, he will be shown with an error message.
20 $fmsg = "Invalid Login Credentials.";
21 }
22 }
23 //3.1.4 if the user is logged in Greets the user with message
24 if (isset($_SESSION['username'])){
25 $username = $_SESSION['username'];
26 echo "Hai " . $username . "
27 ";
28 echo "This is the Members Area
29 ";
30 echo "<a href='logout.php'>Logout</a>";
31

5 sur 22 13-02-20 à 22:03


5 Easy Steps to Create Simple & Secure PHP Login Script - Free https://codingcyber.org/simple-login-script-php-and-mysql-64/

32 }else{
33 //3.2 When the user visits the page first time, simple login form will be displayed.
34 ?>

Logout.php
1 <?php
2 session_start();
3 session_destroy();
4 header('Location: login.php');
5 ?>

Complete Code of login.php


1 <?php  //Start the Session
2 session_start();
3 require('connect.php');
4 //3. If the form is submitted or not.
5 //3.1 If the form is submitted
6 if (isset($_POST['username']) and isset($_POST['password'])){
7 //3.1.1 Assigning posted values to variables.
8 $username = $_POST['username'];
9 $password = $_POST['password'];
10 //3.1.2 Checking the values are existing in the database or not
11 $query = "SELECT * FROM `user` WHERE username='$username' and password='$password'";
12
13 $result = mysqli_query($connection, $query) or die(mysqli_error($connection));
14 $count = mysqli_num_rows($result);
15 //3.1.2 If the posted values are equal to the database values, then session will be created for the
16 if ($count == 1){
17 $_SESSION['username'] = $username;
18 }else{
19 //3.1.3 If the login credentials doesn't match, he will be shown with an error message.
20 $fmsg = "Invalid Login Credentials.";
21 }
22 }
23 //3.1.4 if the user is logged in Greets the user with message
24 if (isset($_SESSION['username'])){
25 $username = $_SESSION['username'];
26 echo "Hai " . $username . "
27 ";
28 echo "This is the Members Area
29 ";
30 echo "<a href='logout.php'>Logout</a>";
31
32 }else{
33 //3.2 When the user visits the page first time, simple login form will be displayed.
34 ?>
35 <html>
36 <head>
37 <title>User Login Using PHP & MySQL</title>
38
39 <!-- Latest compiled and minified CSS -->
40 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
41
42 <!-- Optional theme -->
43 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min
44
45 <link rel="stylesheet" href="styles.css" >

6 sur 22 13-02-20 à 22:03


5 Easy Steps to Create Simple & Secure PHP Login Script - Free https://codingcyber.org/simple-login-script-php-and-mysql-64/

46
47 <!-- Latest compiled and minified JavaScript -->
48 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
49 </head>
50 <body>
51
52 <div class="container">
53       <form class="form-signin" method="POST">
54       <?php if(isset($fmsg)){ ?><div class="alert alert-danger" role="alert"> <?php echo $fmsg
55         <h2 class="form-signin-heading">Please Login</h2>
56         <div class="input-group">
57   <span class="input-group-addon" id="basic-addon1">@</span>
58   <input type="text" name="username" class="form-control" placeholder="Username" required
59 </div>
60         <label for="inputPassword" class="sr-only">Password</label>
61         <input type="password" name="password" id="inputPassword" class="form-control" placeholder
62         <button class="btn btn-lg btn-primary btn-block" type="submit">Login</button>
63         <a class="btn btn-lg btn-primary btn-block" href="register.php">Register</a>
64       </form>
65 </div>
66
67 </body>
68
69 </html>
70 <?php } ?>

If you want to learn other things you can read other posts – registration, login, user login
with activation check, and sending forgotten password by email, Check Username
Availability .

(ii). Steps to create Advanced Login


Script System in PHP and MySQL
In the above simple login script, we have some �aws. That is I’m using plain text passwords
and it is easy to do SQL injections and lot more. Because that is targetted to beginners for
learning purpose.

Here in this advanced login system, you will learn a lot of advanced things and some of the
features are below.

Login with User Name or E-Mail


Securing Login from SQL injections
Encrypting Users Password
Login using PHP Sessions
Only Active Users Can Login

7 sur 22 13-02-20 à 22:03


5 Easy Steps to Create Simple & Secure PHP Login Script - Free https://codingcyber.org/simple-login-script-php-and-mysql-64/

In this script we will start by checking the session, if the user already logged in he will be
redirected to index.php page that is members area. After the form submission, we check
post superglobal isset and not empty. In this code, I’m using DB connection from above
code, database table and HTML form from our above code.

Here I’m just working on improving PHP logic from above code.

Below is the Video on Advanced & Secure PHP


User Login Registration Script With All Features

Subscribe on Youtube

Vivek Vengala

YouTube 1 k

If the post superglobal is set and not empty, if it’s true I’m assigning the submitted values to
variables using this code and encrypting password to md5 hashing instead of plain text
password.

1 if(isset($_POST) & !empty($_POST)){


2   $username = mysqli_real_escape_string($connection, $_POST['username']);
3   $password = md5($_POST['password']);
4 }

After that, I’m writing an SQL query to check the user details in database tables with

8 sur 22 13-02-20 à 22:03


5 Easy Steps to Create Simple & Secure PHP Login Script - Free https://codingcyber.org/simple-login-script-php-and-mysql-64/

submitted user information. Executing the query and also counting the number of rows in
result set. If the number of rows is equal to one then we will set the session and redirect the
user to members area page. Otherwise, we will display an error message. I’m already
displaying these messages in above the form HTML code, if you are following from above
you will already have it.

1 $sql = "SELECT * FROM `user` WHERE username='$username' AND password='$password'";


2 $res = mysqli_query($connection, $sql);
3 $count = mysqli_num_rows($res);
4
5   if($count == 1){
6     $_SESSION['username'] = $username;
7     header('location: members/index.php');
8   }else{
9     $fmsg = "User does not exist";
10   }

And next important cocept is user will be able to login with username or email. For that I’ll
modify the SQL query little bit. So, that we will check the submitted value if it’s email we will
check it with email column. If it’s not email we will check it in username column. And I’m
creating SQL query over couple of conditions and statments.

1 $sql = "SELECT * FROM `user` WHERE ";


2   if(filter_var($username, FILTER_VALIDATE_EMAIL)){
3     $sql .= "email='$username'";
4   }else{
5     $sql .= "username='$username'";
6   }
7 $sql .= " AND password='$password'";

Checking the user, if his account is activated then only we will allow hime to login otherwise
he won’t be able to login. For that I’m using active column, if the user activates his account
by verifying his email. Then only his account status becomes active, that means active
column becomes to 1.

Here is the improved code with above discussed condition.

1 $sql = "SELECT * FROM `user` WHERE ";


2   if(filter_var($username, FILTER_VALIDATE_EMAIL)){
3     $sql .= "email='$username'";
4   }else{
5     $sql .= "username='$username'";
6   }
7 $sql .= " AND password='$password' AND active=1";

Complete code of Advanced Login Script System in


PHP & MySQL

9 sur 22 13-02-20 à 22:03


5 Easy Steps to Create Simple & Secure PHP Login Script - Free https://codingcyber.org/simple-login-script-php-and-mysql-64/

1 if(isset($_POST) & !empty($_POST)){


2   $username = mysqli_real_escape_string($connection, $_POST['username']);
3   $password = md5($_POST['password']);
4   $sql = "SELECT * FROM `user` WHERE ";
5   if(filter_var($username, FILTER_VALIDATE_EMAIL)){
6     $sql .= "email='$username'";
7   }else{
8     $sql .= "username='$username'";
9   }
10   $sql .= " AND password='$password' AND active=1";
11   $sql;
12   $res = mysqli_query($connection, $sql);
13   $count = mysqli_num_rows($res);
14
15   if($count == 1){
16     $_SESSION['username'] = $username;
17     header('location: members/index.php');
18   }else{
19     $fmsg = "User does not exist";
20   }
21 }

Download the Complete Code

This conte nt is locke d


Please support us, use one of the buttons below to unlock the content.

Like 11Klike Follow f ollow


4,347 followers Shareshare
164

Youtube
YouTube 1 k

Next Steps After User Login


Password Encryption
Instead of md5 hashing algorithm, use password_verify PHP function in conjection with
password_hash PHP fucntion. This password_hash should be used while registering users
and while login you can use password_verify PHP function.

I hope this article helped you to learn user login using PHP and MySQL . To get latest news
and updates follow us on twitter & facebook, subscribe to newsletter. If you have any
feedback please let us know by using comment form.

10 sur 22 13-02-20 à 22:03


5 Easy Steps to Create Simple & Secure PHP Login Script - Free https://codingcyber.org/simple-login-script-php-and-mysql-64/

simple login form in php php login script simple login form in php with mysql database
simple php login script simple login php simple login page in php login php mysql simple
php login php login code php simple login

Join Course PHP User


Login Registration
Script With All
Features
With 4 hours of Video content covering
all the features, you can download the
complete source code.

Join Now for $10

Share this:

Tweet 34 Share  More

Vivek Vengala Updated January 26, 2020 PHP

Re late d Posts

11 sur 22 13-02-20 à 22:03


5 Easy Steps to Create Simple & Secure PHP Login Script - Free https://codingcyber.org/simple-login-script-php-and-mysql-64/

How to Create Secure User Login Script in PHP PDO – Free Download

Complete User Authentication System in CodeIgniter – 9 Steps

Do you want to Develop Content Management System in PHP?

8 Simple Steps to Create CRUD Application in OOP PHP

12 sur 22 13-02-20 à 22:03


5 Easy Steps to Create Simple & Secure PHP Login Script - Free https://codingcyber.org/simple-login-script-php-and-mysql-64/

Develop Secure Applications with PHP PDO – Ultimate Guide

Learn How to Improve PHP Security with these 6 Steps?

How to Create Simple CRUD Application in PHP PDO – 7 Easy steps

Do you Know How to Secure PHP Forms with CSRF Tokens?

Viv e k Ve ngala
Vivek Vengala is a Online Entrepreneur, Web Developer from Hyderabad
India.

13 sur 22 13-02-20 à 22:03


5 Easy Steps to Create Simple & Secure PHP Login Script - Free https://codingcyber.org/simple-login-script-php-and-mysql-64/

Click Here to Leave a Comment Below 28 comments

Max

Step 5 add a “?>” in the end : )

Reply

Alan

how do i log out?

Reply

Onutu Mihai

session_destroy();

Reply

Sarah Ellix

Do you have any code for logging out?

Reply

62arts

session_destroy();

Reply

14 sur 22 13-02-20 à 22:03


5 Easy Steps to Create Simple & Secure PHP Login Script - Free https://codingcyber.org/simple-login-script-php-and-mysql-64/

stu�trivia

dude thank uuuuuu… after 2 dayss of sur�ng .. my code working …!!!


greatest website everr ..!!!! haha �

Reply

ganesh

Nice job Its helpful code for beginners

Reply

Dennis Briggs

Very nice on the html form after register I added forgot password line
Forgot Password

Reply

Vivek Vengala

Thanks Dennis, for your valuable suggestions.

Reply

Jomar

Hi, I’m having a problem in 3. 9. Username and Email Checking in


Database. Nothing pops up “Username or Email already exist” when I
create a new duplicate account and I’m confused about your table user.
I thought your only table is usermanagement. Is your usermanagement

15 sur 22 13-02-20 à 22:03


5 Easy Steps to Create Simple & Secure PHP Login Script - Free https://codingcyber.org/simple-login-script-php-and-mysql-64/

table is similar to your user table???? I’m really confused. Thanks

Reply

Vivek Vengala

Hello Jomar,

Please check you have inserted rows in database table or not?

User table is for my development purpose.

Reply

mony

Hi dear,
It works perfectly but when a user logout and then again he click on
login button “which will take him to login page ” it took him directly to
the user dashboard using old stored details.

How to prevent accessing page directly if I have the URL. so you always
be redirected to login page if you are not already logged in may be
setting sessions . can you help please ?

Reply

Vivek Vengala

Hi mony,

Check the session in members area page, if session does not


exist redirect user to login page using header PHP function.

16 sur 22 13-02-20 à 22:03


5 Easy Steps to Create Simple & Secure PHP Login Script - Free https://codingcyber.org/simple-login-script-php-and-mysql-64/

Reply

Andrew

I have this error

Parse error: syntax error, unexpected end of �le in D:\Xampp\htdocs


\usermanagement\login.php on line 66

at line 66 it’s the end of the html tag ()

Reply

Vivek Vengala

Hi Andrew,

Please post your code, so that I can see the problem clearly.

To �x unexpected end of �le error, please check you are not


missing any closing braces for if condition.

Reply

Minitek

Hi Vivek, excellent tutorial.


I am having issues with mysqli_num_rows for login code. I get the
following error message: “Warning: mysqli_num_rows() expects
parameter 1 to be mysqli_result, boolean given in C:\xampp\htdocs
\test\login\login.php on line 9”,

And line 9 code is $count = mysqli_num_rows($result);


It is supposed to return 1, but apparently it doesn’t, which means that

17 sur 22 13-02-20 à 22:03


5 Easy Steps to Create Simple & Secure PHP Login Script - Free https://codingcyber.org/simple-login-script-php-and-mysql-64/

$result query returned false. And i, for the life of me, can’t �gure out
why.
My code is as follows:

**(note i have changed the names of variables a bit, but everything else
is the same as your code shown in the video, at least as far as i can
see).

Reply

Vivek Vengala

Please check the SQL query, if there are no errors use this below
code with mysqli_query()

mysqli_query($connection, $sql) or
die(mysqli_error($connection));

By using above code, you can get the error… If your problem
didn’t solve please let me know…

Reply

Zayn

your are amazing! thanks for this i need to learn more


from you!!!

Reply

lauro

Hello all i was wondering something i manage to get the code to work
??

18 sur 22 13-02-20 à 22:03


5 Easy Steps to Create Simple & Secure PHP Login Script - Free https://codingcyber.org/simple-login-script-php-and-mysql-64/

lets say i have a website and i want to use this “login” how do i send my
members to MYpage once they register ? could someone please help
me on this ?

Reply

Vivek Vengala

Hi lauro,

In successful registration condition block, create session &


redirect the user to members page.

Reply

hixtox

thanks for your Reply .


but the problem was that my server provider does not
accept mysql commands
so i used mysqli
thank you so much .

Reply

hixtox

login html works �ne


but when submitting

Table ‘test.user’ doesn’t exist

i used

19 sur 22 13-02-20 à 22:03


5 Easy Steps to Create Simple & Secure PHP Login Script - Free https://codingcyber.org/simple-login-script-php-and-mysql-64/

:::; $sql = “SELECT * FROM user WHERE username =’$username’ and


password =’$password'”;

and then i tried to create , test.user , but when i used


::::::::: $sql = “SELECT * FROM test.user WHERE username =’$username’
and password =’$password'”;
i got error
Table ‘test.test.user’ doesn’t exist

Reply

Vivek Vengala

Please check your database credentials in connect.php. Maybe


your database name is di�erent, instead of test.

Reply

Ishara

After sur�ng 2 days �nally found the working one for new mysql
version. The best tutorial found over the internet. Thank you. You
saved my day �

Reply

om

Interesting….
But that isn’t secure login! First escaping the variables then match
password with strcmp and password encryption is required. Using
password_hash will be ok and at the time login verify with
password_verify function. Wish you a good luck!

20 sur 22 13-02-20 à 22:03


5 Easy Steps to Create Simple & Secure PHP Login Script - Free https://codingcyber.org/simple-login-script-php-and-mysql-64/

Reply

Vivek Vengala

Hi Om Prakash,

You raised a good point, this tutorial is intended only for


beginner level learners and indeed I’ve discussed the topics
about secure password hash concept and there are other points
like using PDO for securing from SQL Injections. And also using
secure sessions. You can learn more about PHP Security here.

Reply

rajni

Hi

Thanks for the wonderful post. It is very helpful. Just one thing I am
looking for i.e redirecting to another page if the user successfully
logged in. It will be very great if you guide me.

Regards,
Rajni

Reply

Vivek Vengala

Hi Rajni, you can use header PHP function to redirect users after
login.

Reply

21 sur 22 13-02-20 à 22:03


5 Easy Steps to Create Simple & Secure PHP Login Script - Free https://codingcyber.org/simple-login-script-php-and-mysql-64/

Leave a Reply:
Name* Email* W ebsite

Save my name, email, and website in this browser for the next time I comment.

Notify me of follow-up comments by email.

Notify me of new posts by email.

SUBMIT

© 2013 - 2019 Coding Cyber. All Rights Reserved.

22 sur 22 13-02-20 à 22:03

Вам также может понравиться