php login script

To create an authentication or login system with php you will need

A database, a table called users with at least three columns: id, username, password
A HTML form where users fill in their usernames and passwords
A PHP script that will check if usernames and passwords provided actually exist or right
A private area users can access only if successfully logged in.

Login HTML Form Page

<form method="post" action="">
 <p><label for="u_name">username:</label></p>
 <p><input type="text" name="u_name" value=""></p>
 <p><label for="u_pass">password:</label></p>
 <p><input type="password" name="u_pass" value=""></p>
 <p><button type="submit" name="go">log me in</button></p>
<!-- A paragraph to display eventual errors -->
<p><strong><?php if(isset($error)){echo $error;} ?></strong></p>

Login Form PHP Script

// session started
//connect to server
$dbc = mysqli_connect('localhost','root','') or 
 die('could not connect: '. mysqli_connect_error());

//select db
mysqli_select_db($dbc, 'examples') or die('no db connection');

//check if the login form has been submitted
 $usr = mysqli_real_escape_string($dbc, htmlentities($_POST['u_name']));
 $psw = SHA1($_POST['u_pass']) ; //using SHA1() to encrypt passwords 
 //step2: create query to check if username and password match
 $q = "SELECT * FROM users WHERE name='$usr' AND pass='$psw' ";
 //step3: run the query and store result
 $res = mysqli_query($dbc, $q);

 //make sure we have a positive result
 if(mysqli_num_rows($res) == 1){
  //starting a session 
 //creating a log SESSION VARIABLE that will persist through pages 
 $_SESSION['log'] = 'in';

 //redirecting to restricted page
 } else {
 //create an error message 
 $error = 'Wrong details. Please try again'; 
}//end isset go

Restricted php page

 <?php #admin/restricted.php 
 #####[make sure you put this code before any html output]#####

//starting the session

//checking if a log SESSION VARIABLE has been set
if( !isset($_SESSION['log']) || ($_SESSION['log'] != 'in') ){
 //if the user is not allowed, display a message and a link to go back to login page
 echo "You are not allowed. <a href="index.php">back to login page</a>";
 //then abort the script

*  CODE FOR LOG OUT click here to see the logout tutorial 


1 thought on “php login script”

Leave a Reply

Related Posts: You may like

Extract Total Number of Image And Missing Alt Attribute using php

How to extract Heading tags using PHP from string

How to remove whitespace from string using php

Remove All Special Characters From String PHP

PHPKIDA Offering Free Tools:


Download Instagram Videos & Photos.

Download Now


Real Time Currency Converter

Convert Now


Robots.txt File Creater

Create Now


Compress yout HTML Code

Minify Now


Compress yout CSS Code

Minify Now


Compress yout JavaScript Code

Minify Now

Sign up for weekly update

Milkshake is almost ready. If you're interested in testing it out, then sign up below to get exclusive access.