This is tutorial is sequential of previous PHP tutorial. If you have not check that one please follow that tutorial before starting this one.
PHP Tutorial 2 – Create a simple Login page part 1
In this tutorial, I’m going to cover the server part of the previous tutorial. In last tutorial we saw when “login.php” is submitted via JavaScript it forwarding to “loginController.php”. “loginController.php” will differentiate between different action request coming from “login.php” and also perform database operations.
Contents of this tutorial
- Create a file.
- Full code of “loginController.php”.
- Important parts explained.
1. Create a file :
Under “chat_system” folder create another folder name “controller” as in this folder we will store server side controller scripts. Inside this folder create a file name “loginController.php”. Inside this file we will write PHP scripts which can use to control user login and registration.
File Structure :
chat_systemcontrollerloginController.php
2. Full code of “loginController.php”:
In purpose of this tutorial you can see whole code below, then I will explain each part of this code below so, you can relate how each part is connected.
You can select the whole code by double click anywhere between the code.
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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | <?php include('../config.php'); if (isset($_POST['username']) and isset($_POST['password'])){ switch ($_REQUEST['action']) { case 'registration': $query=$db->prepare("INSERT INTO admin SET username=?, password=?"); $run=$query->execute([$_REQUEST['username'],$_REQUEST['password']]); if ($run) { header("location: ../login.php"); exit; } break; case 'login': session_start(); if($_SERVER["REQUEST_METHOD"]=="POST"){ $username= $_REQUEST['username']; $password = $_REQUEST['password']; /* This sql query is needed if you want to login if user entered username or email $query="SELECT * FROM admin WHERE "; if(filter_var($username,FILTER_VALIDATE_EMAIL)){ $query.="email='$username'"; } else{ $query.="username='$username'"; } $query.="AND password='$password'"; */ $query=$db->prepare("SELECT id FROM admin WHERE username =? and password =?"); $run=$query->execute([$username,$password]); $rs=$query->fetchall(PDO::FETCH_OBJ); $count=$query->rowCount(); if ($count) { $_SESSION['username']=$username; header("location: ../index.php"); exit; } else { $_SESSION['error']="faild"; header("location: ../login.php"); exit; } } break; } } else { header("location: ../login.php"); exit; } ?> |
3. The important thing you need to know (explained):
include('../config.php'):
include is used to include contents of other file PHP file to another PHP file. If you are familiar with C or C++ then you can see include as #include, both work in the same manner. In this case “config.php” file stores database configuration details which we need in this file, that’s why we are including “config.php” into “loginController.php” .
if(isset($_POST['username'])and isset($_POST['password'])) :
isset() method is used to check that parameters are set or not. isset() will return FALSE if testing a variable that has been set to NULL. Here we are checking any value is set to ‘username’ and ‘password’ or not. If no values are set than if condition will fail and the page will redirect to “login.php”.
switch($_REQUEST['action']) :
the switch statement is a condition checking statement. It’s similar to a serious of IF statement
on the same expression. switch statement offers more clean coding when dealing which checking different values with the same variable.
Here we used a switch statement to check which type of action is requesting “login.php”. When we are submitting the form to the login page before that we are changing the action of that form.
As we can see on part 2 “action=registration”, this how we setting action in “login.php”. Now in the controller, we are searching for that action checking its value. This how two pages are connected with each other.
case 'registration':
If registration button is clicked the case ‘registration’ will be true and registration part is performed.
$query=$db->prepare("INSERT INTO admin SET username=?,password=?"):
$db->prepare() is used to prepare MySQL statement before executing it. In the prepared statement, we are preparing an insert query on admin. If this query executed it will search for username and password values when those values are passed it will insert a record at admin table.
$run=$query->execute([$_REQUEST['username'],$_REQUEST['password']]):
$query->execute() will execute the query which has been prepared by $db->prepare(). As we discussed before as we use ‘?’ in our query, it will wait for username and password to pass. That’s why when we are executing that query we are providing username and password values given by “login.php”.
If the query is executed perfectly then it will return 1. This value will be stored at $run.
header("location: ../login.php"):
If everything is ok and user registered successfully then the user will be redirected to login.php.
session_start():
the session is a unique way to store information which can be used on multiple pages. To use a session we have to start a session first. session_start() checks if a session is already started and if none of started it starts one.
$_SESSION['username']=$username:
Here we are creating a session username which will store the value of username. When creating a session it always follow this syntax,
$_SESSION[‘session name’]= value to be stored
$count=$query->rowCount():
$query->rowCount() returns how many rows are present in the recordset. In 46 no line its used to count any rows is selected or not. If any rows are selected after query execution that means username and password are valid.
This is tutorial ends here. It’s only created to help you learn basic of PHP login process if you want to learn more about it tell me comments.
I would like to hear from you, tell me in comments below if you have any queries or feedback. Thank you.
This is really helpful! Thank you for sharing this. 🙂
I'm glad that you found this information helpful 🙂