Simple HTML Login Form Using PHP

Many sites use login authentication for user login on their site so they use login forms which take username or email and password from the user and check that info in the database and if it was matched with data in the database then allow them to sign in and if not throw back them on the login page.

Login Pages are created in HTML and designed through CSS which we already covered in the last topic.

In that topic, we take simple login form and take two input fields and a login button. Now today we will learn, how it works. The code of login form is:

Now three things to remember. One is action, method and name attribute in input fields.

Action: this attribute tells us where to submit the data when the submit button is clicked.

Method: which method we are using GET, POST, FILE for moving the variable to any other page, so today we use POST method.

Name: it’s the attribute of the input field and we gave then some value and that value is used later to get the data from HTML input fields in PHP.

As in the form we have two input fields name user and pass. We are using POST method and action page is demo.php so when we click on submit button the values of input fields store in POST array and send to PHP page where we have to extract them.

$_POST is used to get data when we are using POST method in HTML forms. So to get data in username field we write $_POST [“user”] and store it in a variable like $a and the same process is used for the password. Then check them with the password we save in code, this time, we don’t use the database and hard code the username and password in PHP code.

1

2

3

4

<?php

$a=$_POST["user"];

$b=$_POST["pass"];

?>

Now to check we use if else statement. As in my case I set user name and password values equal to “admin” and the user does not enter right values an alert show invalid credentials.

isset() in PHP:

isset() in PHP is used to check whether the value of any variable i.e. GET or POST is set or not? otherwise, it gives an error for unknown values of GET or POST.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

<?php

if(isset($_POST["user"])&&isset($_POST["pass"]))

{

$a=$_POST["user"];

$b=$_POST["pass"];

if($a!=""&&$a==="admin"){

if($b!=""&&$b==="admin")

{

?>

<script>

alert("Login Successful");

</script>

<?php

}

else{

?>

<script>

alert("invalid credentials");

</script>

<?php

}

}else{

?>

<script>

alert("invalid credentials");

</script>

<?php

}

}

?>

To avoid user errors it’s a best to write all the code in try catch block so that system should we fault tolerated. We discuss all these one by one in PHP it’s just an introduction topic to make know how to use PHP that what is it? and for what it is used for?

Complete Code: (Copy this code and paste in a new PHP file i.e. “loginphpdemo.php” file)