EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

Login Page in PHP

By Priya PedamkarPriya Pedamkar

Home » Software Development » Software Development Tutorials » PHP Tutorial » Login Page in PHP

Login Page in PHP

Introduction to Login Page in PHP

It will be seldom found that an engaging website doesn’t propose an account creation from its customers. In order to do so, they need to have the facilities for a new user to register themselves, and later on login and interact with the website using their account. PHP exposes enough utilities to set up a functional Login Page, quickly, which can also scale later on as when required. After setting up a basic login form to request the credentials, the same PHP script can be used to process and validate the credentials, and redirect to the appropriate page on successful login. It also provides options for creating and storing cookies and sessions, to track users once they have completed the login process.

How do Login Pages Work in PHP?

PHP is a scalable stateless server-side scripting language. It allows one to capture form data by storing them in arrays $_GET or $_POST depending on whether the method used while submitting the form is GET or POST. Generally, the post method is preferred due to security reasons. Upon submission, these arrays can be indexed by the input field names to get the specific value.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

For login forms, the credentials are passed and stored in these arrays, which more often than not, is just a set of usernames and passwords. Based on the requirement, either the username & password combination can be directly validated in the PHP code itself, or the valid set of username, password combinations might be stored in a database which could be looked up.

Setting up the Login Page

Let’s create a page, Login.php containing the following HTML lines:

Code:

<html>
<head>A sample login page</head>
<body>
<h2>Enter Login Information:</h2><br>
<form action="" method="post">
<label>Username : </label><input type="text" name="username" /><br/>
<label>Password : </label><input type="password" name="pwd" /><br/>
<input type="submit" value="Login" />
</form>
</body>
</html>

Output:

Login Page in PHP 1-1

These lines create a very simple form, requiring a user to enter two fields, a username, and a password. It provides a third input, which is a submit button and causes form data, i.e. username and password, be sent to the location mentioned in the action attribute of the form tag. Since it’s empty above, it passes the form information to the same PHP page.

Popular Course in this category
PHP Training (5 Courses, 3 Project)5 Online Courses | 3 Hands-on Project | 28+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (6,123 ratings)
Course Price

View Course

Related Courses
Java Servlet Training (6 Courses, 12 Projects)All in One Software Development Bundle (600+ Courses, 50+ projects)

How to Create a Login Page in PHP?

The above page is static HTML code, without actually validating the user or login the person to internal web-pages. In order to do so, we need to process the values passed in the fields username and pwd stored in $_POST because of the method posts. Thus the values are present can be checked using:

Code:

<?php
$error = "";
if(isset($_POST['username']) && isset($_POST['pwd'])){
// check for validity
}
?>

Upon verifying at both inputs are indeed present, we can validate their values and redirect a person to the appropriate welcome page. We can achieve this by inserting following simple piece of code within the if-statement block shown above:

Code:

$username = $_POST['username'];
$password = $_POST['pwd'];
if($username == "admin" && $password == "l0G3In"){
header(‘location: Home.php’);
}
else {
$error = "Invalid username or password!";
}

With the above lines, once the user has submitted a valid set of credentials, he’s allowed access to home.php, or we store an error message which can be shown to the user.

Session

We don’t want a user to repeatedly login in upon every request. Thus we need to keep track of users who have logged in, irrespective of the page they are requesting. One way of achieving this in PHP is using sessions.

Briefly, sessions are a server-side small piece of information, temporarily stored for a client, once the page is requested. In PHP this is achieved by calling function session_start() as the first line in the script. From next time the page is accessed, session_start() doesn’t create a new session but retrieves information of the session started earlier and stores in a special array $_SESSION.

Values to be passed across pages while a session is active can be set in a similar fashion to a normal array and isset() function can be used to check if a particular value is available within the array.

Combining all the things discussed, the code will look as follows:

Code:

<?php
session_start();
if(isset($_SESSION["login"]) && $_SESSION["login"]==True){
header('location: Home.php');
}
$error = "";
if(isset($_POST['username']) && isset($_POST['pwd'])){
$username = $_POST['username'];
$password = $_POST['pwd'];
if($username == "admin" && $password == "l0G3In"){
header(‘location: Home.php’);
}
else {
$error = "Invalid username or password!";
}
}
?>
<html>
<head>A sample login page</head>
<body>
<h2>Enter Login Information:</h2><br>
<?php echo $error;?>
<form action="" method="post"><label>Username : </label><input type="text" name="username" /><br/>
<label>Password : </label><input type="password" name="pwd" /><br/>
<input type="submit" value="Login" />
</form>
</body>
</html>

Output:

login info

Home.php

Now, any other page which requires a login just needs to check that the session key login is set. If not, the user can be redirected to the login page. Else he has access to the secret internal content. Let’s create one for demo purposes:

Code:

<?php
session_start();
if(!isset($_SESSION["login"]) || $_SESSION["login"]!=True){
header('location: Login.php');
}
?>
<html>
<head>Welcome to User's Home Page</head>
<body>
<h2>Wishing you a good day!!</h2><br>
</body>
</html>

Output:

Home.php

The above code first retrieves the session details by invoking session_start(). It then validates that the session is still active for a user who had completed the login process. If not, the user is sent to the Login.php page. If the user had successfully logged in, the rest of the content is available to the user.

Conclusion

It’s extremely easy to create login pages in PHP. Here we have directly stored the credentials in the script, but ideally (and most commonly) they will be stored in some form of a database or key manager. Also, here we used sessions, which are stored on the browser side, but you can use cookies which are stored on the browser (client) side but are less reliable.

Recommended Articles

This is a guide to Login Page in PHP. Here we discuss how to create a login page in PHP with working and code implementation. You may also look at the following articles to learn more –

  1. Why we use Filters in PHP?
  2. PHP File Handling Functions
  3. Types of Multidimensional Array in PHP
  4. How to Create Forms in PHP?

All in One Software Development Bundle (600+ Courses, 50+ projects)

600+ Online Courses

50+ projects

3000+ Hours

Verifiable Certificates

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
PHP Tutorial
  • Programs
    • Patterns in PHP
    • Star Patterns in PHP
    • Swapping in PHP
    • Fibonacci Series PHP
    • Factorial in PHP
    • Reverse String in PHP
    • Square Root in PHP
    • Random Number Generator in PHP
    • Palindrome in PHP
    • Prime Numbers in PHP
    • Armstrong Number in PHP
    • Socket Programming in PHP
    • Login Page in PHP
    • PHP Login Template
    • PHP Object to String
  • PHP Basic
    • Introduction To PHP
    • What is PHP
    • PHP Keywords
    • Advantages of PHP
    • Career In PHP
    • Comments in PHP
    • PHP Commands
    • PHP Frameworks
    • PHP Compiler
    • Variables in PHP
    • PHP Superglobal Variables
    • PHP Versions
    • Object in PHP
    • PHP Object Injection
    • What is Drupal
    • Top PHP Frameworks
    • WebStorm IDE
    • What is phpMyAdmin?
    • PhpStorm
    • Install phpMyAdmin
    • Phalcon Model
  • Data Types
    • PHP Data Types
    • PHP Integer
    • PHP Booleans
  • Operators
    • PHP Operators
    • Arithmetic Operators in PHP
    • Comparison Operators in PHP
    • Logical Operators in PHP
    • Bitwise Operators in PHP
    • Ternary Operator in PHP
    • PHP String Operators
  • Control Statements
    • Control Statement in PHP
    • PHP if Statement
    • if else Statement in PHP
    • elseif in PHP
    • PHP Switch Statement
    • Continue in PHP
    • Break in PHP
  • Loops
    • PHP Loops
    • For Loop in PHP
    • PHP Do While Loop
    • PHP While Loop
    • While Loop in PHP
    • Foreach Loop in PHP
  • Constructor
    • Constructor in PHP
    • Destructor in PHP
  • State Management
    • Cookie in PHP
    • Sessions in PHP
  • Array
    • What is PHP Array
    • Arrays in PHP
    • 2D Arrays in PHP
    • Associative Array in PHP 
    • Multidimensional Array in PHP
    • Indexed Array in PHP
    • PHP Array Functions
    • PHP unset Array
    • PHP Append Array
    • PHP Array Search
    • PHP Split Array
    • PHP array_push()
    • PHP array_pop()
  • Functions
    • Functions in PHP
    • PHP Math Functions
    • PHP Recursive Function
    • PHP String Functions
    • Hashing Function in PHP
    • Date Function in PHP
    • PHP Anonymous Function
    • Calendar in PHP
    • PHP Call Function
    • PHP Pass by Reference
    • PHP list
    • PHP ucfirst()
    • PHP ucwords()
    • trim() in PHP
    • isset() Function in PHP
    • PHP replace
    • PHP fpm
    • preg_match in PHP
    • PHP preg_replace()
    • PHP ob_start()
    • PHP Reflection
    • PHP Split String
    • PHP URL
    • PHP preg_match_all
    • PHP strtoupper()
    • PHP preg_split()
    • PHP substr_replace()
    • PHP setlocale()
    • PHP substr_count()
    • PHP Serialize
    • PHP strlen()
    • PHP async
    • PHP Date Time Functions
    • PHP timezone
    • PHP Data Object
    • print_r() in PHP
    • PHP header()
    • PHP strip_tags()
    • PHP chop()
    • PHP MD5()
    • PHP unset()
    • PHP crypt()
    • PHP wordwrap()
    • PHP is_null()
    • PHP strtok()
    • PHP bin2hex()
    • PHP parse_str()
    • PHP levenshtein()
    • PHP addslashes()
    • PHP strtotime
    • PHP strpos
    • PHP sha1()
    • PHP explode()
    • PHP sscanf()
    • PHP require_once
    • PHP Zip Files
    • PHP $_SERVER
    • PHP $_POST
    • PHP Include and Require
    • PHP POST Method
  • Advanced
    • Overloading in PHP
    • Overriding in PHP
    • Method Overloading in PHP
    • Inheritance in PHP
    • Multiple Inheritance in PHP
    • PHP Interface
    • Encapsulation in PHP
    • PHP Constants
    • PHP Magic Constants
    • PHP Regular Expressions
    • PHP GET Method
    • PHP Annotations
    • PHP Encryption
    • PHP file Functions
    • PHP readfile
    • PHP?Write File
    • PHP Append File
    • PHP Type Hinting
    • PHP Filters
    • PHP Float
    • PHP Form
    • PHP Form Builder
    • PHP Form Validation
    • Sorting in PHP
    • PHP usort()
    • Sort string PHP
    • PHP Stack Trace
    • PHP Stack Overflow
    • PHP Pagination
    • PHP implode
    • Polymorphism in PHP
    • Abstract Class in PHP
    • PHP Final Class
    • PHP Custom Exception
    • error_reporting() in PHP
    • PHP Log Errors
    • Access Modifiers in PHP
    • PHP Change Date Format
    • Static Method in PHP
    • PHP File Handling
    • PHP Output Buffering
    • Get IP Address in PHP
    • PHP Open File
    • Upload a File in PHP
    • String in PHP
    • Public Function in PHP
    • Private in PHP
    • Protected in PHP
    • basename in PHP
    • Validation in PHP
    • PHP mail()
    • PHP Email Form
    • PHP Directory
    • PHP Create Session
    • PHP include_once
    • PHP json_decode
    • PHP XMLWriter
    • PHP XML Reader
    • PHP XML Parser
    • PHP XML into Array
    • Phalcon Framework
  • Database
    • PHP Database Connection
    • How to Connect Database to PHP
  • Interview Questions
    • PHP Interview Questions
    • PHP OOP Interview Questions
    • CakePHP Interview Questions
    • Core PHP Interview Questions

Related Courses

PHP Training Course

Java Servlet Training

Software Development Course Training

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - PHP Training Course Learn More