Friday, March 7, 2014

Share It

PHP simple login script

Hi dear friends, we have discussed about deleting a file using PHP script in our previous tutorial. In this tutorial I am going to explain you about login script using PHP. Login is used in applications where a user needs to be authenticated to access an application. This tutorial will give you the basic login form. I have used MySql to connect to the database where the login details are stored.

I have three PHP files where the first file contains the login form, the second contains the process for login form and the third file is the one where you will be redirected after login is successful.

Now let us see these files and let me explain them in detail. Please follow these carefully.

login.php

As I said there are three files. Login.php is the first file that contains login form. Let us see the code for it.

login.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="te-IN">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Login</title>
</head>
<body>

<?php  if(@$_REQUEST['msg']=='fail')
 {
 echo"<div style='color:red;'>User name or password invalid.</div>";
 }


?>
<style>
.login_field
{
border:2px solid rgb(168, 168, 168);
border-radius:8px;
box-shadow:1px 0px 9px rgb(110, 110, 110);
color:rgb(153, 153, 153);
font-size:14px;
height:20px;
padding:4px;
}
</style>
<h1>Login</h1>

<form action="login_a.php" method="post" style="clear:both;">
<table>
<tr><td>Email</td><td><input type="text" name="email" id="email" class="login_field"></td>
</tr></br>

<tr><td>Password</td><td><input type="password" name="pwd" id="pwd" class="login_field"></td>
</tr></br>

<tr>
<td><input type="submit" name="login" value="login" onClick="return validate()"></td>
</tr>
</table>
</form>
</body>
</html>
In the above code we have HTML form which is used to fill the email and password. It contains input fields of text and submit button. In the <form> tag you can see action.  It tells the form to perform an action. We have to supply a file name on which the action has to be performed.

Next you can see method  It tells the form whether to POST or GET. There are three form methods POST, GET and REQUEST. Method will send the form values to the file which performs an action.

Name attributes inside input tags are used to get the values in the text boxes.

$_REQUEST['msg']=='fail'  checks whether the get method has the value fail for msg and if it is true then it prints "User name or password invalid". The request method will be executed when the username or password is wrong.

Copy the above code and save it as login.php

Now lets have a look on the second file which performs the action for login.

login_a.php

<?php
session_start();
include "db.php";

 if(isset($_REQUEST['login']))
 {

 $email = $_POST['email'];
 $password = $_POST['pwd'];
 $check = mysql_query("select * from user where email='$email' and password= BINARY '$password'")or die(mysql_error());
 $ret = mysql_fetch_array($check);
 $count = mysql_num_rows($check);

 if($count==1)
{
$_SESSION['id']=$ret['id'];

header('location:index.php');
exit();

}
else
{
header('location:login.php?msg=fail');
exit();
}
 }

?>
The above code session_start(); is a function that starts a session for the login.
include "db.php"; will import the database file. For database connection file please read How to connect mysql database using PHP, copy the code from there and save it as db.php

isset($_REQUEST['login']) checks whether the form has the name login in the submit button. If yes it will fetch the values from the text boxes of the form.

 $check = mysql_query("select * from user where email='$email' and password= BINARY '$password'")or die(mysql_error()); //checks the email and password whether matching or not. and die(mysql_error()) returns a value if it finds any error in the syntax.

$ret = mysql_fetch_array($check); This line fetches the array from the database.

Here is the logic $count = mysql_num_rows($check); counts for the number of rows in the database matching for the current email and password.

We have unique email or usernames for login. So  if($count==1) checks whether the count is equals to 1.

If yes then it creates a session and redirects you to the next page else you will be taken back to the login page with an error message we discussed above.

Copy and save the second block of code as login_a.php

The next and last page after login is index.php

index.php

<?php
session_start();
 $id = $_SESSION['id'];
 if(empty($_SESSION['id']))
 {
 header('location:login.php');
 exit;
 }

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Home</title>
<link href="css/gallery.css" rel="stylesheet" type="text/css" />

<link rel="stylesheet" type="text/css" href="css/style.css" />

</head>
Welcome
</body>
</html>
As discussed above session_start(); starts a session for this page.

$id = $_SESSION['id']; // session stores id in it.

if(empty($_SESSION['id'])) checks if session expired. If yes the page will be redirected to login.php

Save this code as index.php

The sql for the login script is given below.

CREATE TABLE IF NOT EXISTS `user` (
 

`id` int(5) NOT NULL AUTO_INCREMENT,
  `name` varchar(30) NOT NULL,
 

`email` varchar(30) NOT NULL,
  `password` varchar(15) NOT NULL,
 

PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1

AUTO_INCREMENT=2 ;

--
-- Dumping data for table `user`
--

INSERT INTO

`user` (`id`, `name`, `email`, `password`) VALUES
(1, '', 'admin@admin.com',

'pass');

Run the sql query in phpmyadmin and set the requires database configuration by copying the db.php from here and login to the application using admin@admin.com as email and pass as password.

Thank you very much. Please feel free to ask your queries below.

Note: Spamming comments will be removed.

Author: Bhanu Chander Bathini (CEO, Tricks Town.)
Hey friends, I am Bhanu Chander a Web Designer/Developer, Content writer, Freelance SEO analyst and a blogger. I am pursuing my M.Tech in Computer Science and Engg. You can contact me on bhanu4funn@gmail.com for web design solutions at low cost with effective SEO.

0 comments: