PHP Login Form or Login Script in PHP!!!
If you know how to create website in php and you started creating any php web site that allow user or admin to login then first thing comes in your mind is to create php login script or login form in php that allow user or admin to get login. For login the user must have their respective username and password which he enters in to login form page. To make his successful login we verified his username and password with MySQL database table which contain the username and password for all.
In this tutorial of php code for beginners we will show you step by step creation of your first php login form or php script for login. Basically we create one simple login form in html and connect this code with MySQL database and php script.
You can also use the JavaScript validation or jquery validation for your login php form.
Step 2:- Create a config.php file with the below:
<?php
<?php
include("config.php");
//including config.php in our file
if(!empty($_POST['username']) && !empty($_POST['password'])){
// Now checking user name and password is entered or not.
$user = $_POST['username'];
$pass = $_POST['password'];
$check = "SELECT * from users where username = '".$user."'";
$qry = mysql_query($check);
$num_rows = mysql_num_rows($qry);
if($num_rows > 0){
// Here we are checking if username is already exist or not.
echo "The username you have entered is already exist. Please try another username.";
echo '<a href="signup.php">Try Again</a>';
exit;
}
// Now inserting record in database.
$query = "INSERT INTO users (username,password) VALUES ('".$user."','".$pass."');";
mysql_query($query);
echo "Thank You for Registration.";
echo '<a href="register.html">Click Here</a> to login you account.';
exit;
}
?>
<html>
<head>
<title>Registration Page | Simple login form</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div id="containt" align="center">
<form action="<?php $_SERVER['PHP_SELF']?>" method="post">
<div id="header"><h2 class="sansserif">User Registration</h2></div>
<table>
<tr>
<td>Select Your Username:</td>
<td> <input type="text" name="username" size="20"></td>
</tr>
<tr>
<td>Select Your Password:</td>
<td><input type="password" name="password" size="20"></td>
</tr>
<tr>
<td><input type="submit" value="Sign Up"></td>
</tr>
</table>
</form>
</div>
</body>
</html>
<html>
Step 5:- Create "login.php" file with following code:
<?php
session_start();
echo "You are Welcome ". $_SESSION['user'];
// You can place here the actual test or images you want to show. I have just added welcome message.
?>
If you know how to create website in php and you started creating any php web site that allow user or admin to login then first thing comes in your mind is to create php login script or login form in php that allow user or admin to get login. For login the user must have their respective username and password which he enters in to login form page. To make his successful login we verified his username and password with MySQL database table which contain the username and password for all.
In this tutorial of php code for beginners we will show you step by step creation of your first php login form or php script for login. Basically we create one simple login form in html and connect this code with MySQL database and php script.
You can also use the JavaScript validation or jquery validation for your login php form.
Step 1:- Create a table "users" with the code below:
CREATE TABLE users(
id int NOT NULL AUTO_INCREMENT,
username varchar(16),
password char(16),
PRIMARY KEY(id),
UNIQUE (username)
)
Step 2:- Create a config.php file with the below:
<?php
$database = "mydata"; // the name of the database.
$server = "localhost"; // server to connect to.
$db_user = "root"; // mysql username to access the database with.
$db_pass = ""; // mysql password to access the database with.
$table = "users"; // the table that this script will set up and use.
$link = mysql_connect($server, $db_user, $db_pass);
mysql_select_db($database,$link);
?>
Step 3:- Create "signup.php" file with following code:
include("config.php");
//including config.php in our file
if(!empty($_POST['username']) && !empty($_POST['password'])){
// Now checking user name and password is entered or not.
$user = $_POST['username'];
$pass = $_POST['password'];
$check = "SELECT * from users where username = '".$user."'";
$qry = mysql_query($check);
$num_rows = mysql_num_rows($qry);
if($num_rows > 0){
// Here we are checking if username is already exist or not.
echo "The username you have entered is already exist. Please try another username.";
echo '<a href="signup.php">Try Again</a>';
exit;
}
// Now inserting record in database.
$query = "INSERT INTO users (username,password) VALUES ('".$user."','".$pass."');";
mysql_query($query);
echo "Thank You for Registration.";
echo '<a href="register.html">Click Here</a> to login you account.';
exit;
}
?>
<html>
<head>
<title>Registration Page | Simple login form</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div id="containt" align="center">
<form action="<?php $_SERVER['PHP_SELF']?>" method="post">
<div id="header"><h2 class="sansserif">User Registration</h2></div>
<table>
<tr>
<td>Select Your Username:</td>
<td> <input type="text" name="username" size="20"></td>
</tr>
<tr>
<td>Select Your Password:</td>
<td><input type="password" name="password" size="20"></td>
</tr>
<tr>
<td><input type="submit" value="Sign Up"></td>
</tr>
</table>
</form>
</div>
</body>
</html>
Step 4:- Create "register.html" file with following code:
<html>
<head>
<title>Php Simple Login Form</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div id="containt" align="center">
<form action="login.php" method="post">
<div id="header"><h2 class="sansserif">Admin/Employee Login</h2></div>
<table>
<tr>
<td>Enter Username:</td>
<td> <input type="text" name="username" size="20"></td>
</tr>
<tr>
<td>Enter Password:</td>
<td><input type="password" name="password" size="20"></td>
</tr>
<tr>
<td><input type="submit" value="Log In"></td>
<td><a href="signup.php">Sign Up</a></td>
</tr>
</table>
</form>
</div>
</body>
</html>
Step 5:- Create "login.php" file with following code:
<?php
session_start();
include("config.php"); //including config.php in our file
$username = $_POST["username"]; //Storing username in $username variable.
$password = $_POST["password"]; //Storing password in $password variable.
$match = "select id from $table where username = '".$_POST['username']."'
and password = '".$_POST['password']."';";
$qry = mysql_query($match);
$num_rows = mysql_num_rows($qry);
if ($num_rows <= 0) {
echo "Sorry, there is no username $username with the specified password.";
echo "Try again";
exit;
} else {
$_SESSION['user']= $_POST["username"];
header("location:admin.php");
// It is the page where you want to redirect user after login.
}
?>
Step 6:- Last step is Create "admin.php" file with following code:
Step 6:- Last step is Create "admin.php" file with following code:
<?php
session_start();
echo "You are Welcome ". $_SESSION['user'];
// You can place here the actual test or images you want to show. I have just added welcome message.
?>
Now your PHP login form is ready to use.
Hope this php tutorial is useful for you. Keep following Php Tutorials For Beginners for more help.
Hope this php tutorial is useful for you. Keep following Php Tutorials For Beginners for more help.
great
ReplyDeletegood working very well
thanks bro
great job dude!
ReplyDeleteits only redirecting me in login.php, possible problems?
ReplyDeleteBecause may be you have error in your username or password.
DeleteThanks for the information , because i'm still beginner about php code . by the way which one is login processing ?
ReplyDeletelogin.php is for your login processing.
DeleteThanks on your marvelous posting! I certainly enjoyed reading it, you will be a great Author. I will remember to bookmark your blog and will eventually come back from now on. I want to encourage that you continue your great writing, have a nice day!
DeleteThank you very much really very helpful for me Free Register Login Code
ReplyDeleteHow do i use the Sessions info to control access to other pages?
ReplyDeleteIn above post i have used $_SESSION['user'] to store user name after successful login. On target page(in our case 'admin.php') use can use this session info to show Welcome message to the user.
DeleteTo now more on session variable see this post PHP Session Example and PHP Session Tutorial
How do users register?
ReplyDeleteHey there. Have set this up perfectly, and it works really well! Thank you. However, how can I restrict the access to my pages unless user is logged in?
ReplyDeletenice post .....
ReplyDeletethanks :)
how to use this code to separate admin and user??
ReplyDeleteTo seperate admin and user, you have to set some field in database during new registration process. The registration form contain drop down field to choose "admin" or "user" register.
DeleteHow to direct the user to adminlogin.php if they login as admin and to login.php page if they login as user only. Where the code must be written? in login.html or login.php?
DeleteThank you.
how user register in the same
ReplyDeleteI have not included registration code in this example. But sure i will update this code with registration process in this weekend.
Deletemy database not connected.. plz help
ReplyDeleteCheck your database name is "mydata" or not?
Deletewhen i log.in always say there is no username admin with the specified password. newbie :)
ReplyDeleteNice artical keep on writing for PHP beginner
ReplyDeletejobs in burdwan
Great job my friend, the code is very understandable!
ReplyDeleteBut I have one question.When I run my page through my localhost I get this result "Sorry, there is no username with the specified password.Try again" directly, without inserting an account into my form.Do you have any ideas?
*sorry about the previous post but I had forgotten smothing :)
This is because I have not created user registration page here and sorry for that. In above example only those person can login whose data is available in database.
ReplyDeleteI will make user registration page also as soon as i get the time.
please please please make the registration page soon, i really need it. thank you
ReplyDeleteI have added the code for "User Sign Up". Please check.
DeleteNice article keep on writing What Responsive web Design
ReplyDelete0) { // Here we are checking if username is already exist or not echo "The username you have entered is already exist. Please try another username."; echo 'Try Again'; exit; } // Now inserting record in database. $query = "INSERT INTO users (username,password) VALUES ('".$user."','".$pass."');"; mysql_query($query); echo "Thank You for Registration."; echo 'Click Here to login you account.'; exit; } ?> why this message appear to me in the signup screen
ReplyDeleteMay be you have missed php starting tag ie <?php
DeleteGreat work, thank you very much!
ReplyDeleteOnly one question about the signup.php: i keep getting an error about $_server being an undefined variable... where is it defined? I didn't get that part, what am I doing wrong?
Just turn off your warning form php.ini file.
DeleteIt was my bad actually. I wrote it exactly like in your example $_server['php_self'] when it has to be written with CAPS: $_SERVER['PHP_SELF'] otherwise it won't work.
Deletevery informative.I new to php. Can i get of example of upload file and download uploaded file php code. I am doing simple Online storage.looking forward to your feedback. :)
ReplyDeleteThanks...
DeleteHere is a link for file downloading in php
File Downloading in PHP
Hello again, thank you for updating the code!!
ReplyDeleteI have some questions: First of all I have added 3 additional fields in my database(firstname,lastname,email) and I haven't created the html file, because i'm using the form inside the login.php file.When I'm inserting a new user in my database the message tells me that it is successfull, but there is no new record in the databse.Also when I'm accessing the login page this message appears without inserting anything in my form"Sorry, there is no username with the specified password.Try again" and I don't know why.
Thank you In advance!!!.
Can you show me your code? It will be easy for me to find your issue.
DeleteHere is the code, also today I changed the code to check if all the fields are filled and now the previous message does not apear. 0){
Delete// Here we are checking if username is already exist or not.
echo "The username you have entered is already exist. Please try another username.";
echo 'Try Again';
exit;
}
// Now inserting record in database.
$query = "INSERT INTO users (firstname,lastname,username,password,email) VALUES ('".$first."','".$last."','".$user."','".$pass."".$mail."');";
mysql_query($query);
echo "Thank You for Registration.";
echo 'Click Here to login you account.';
exit;
}
?>
if(!empty($_POST['username']) && !empty($_POST['password']) && !empty($_POST['firstname']) && !empty($_POST['lastname'])
Delete&& !empty($_POST['email'])){
// Now checking user name and password is entered or not.
$first= $_POST['firstname'];
$last= $_POST['lastname'];
$user = $_POST['username'];
$pass = $_POST['password'];
$mail = $_POST['email'];
$check = "SELECT * from users where username = '".$user."'";
$qry = mysql_query($check);
$num_rows = mysql_num_rows($qry);
if($num_rows > 0){
// Here we are checking if username is already exist or not.
You have syntax error in your sql query near '".$pass."".$mail."'. Try to replace with this:-
Delete$query = "INSERT INTO users (firstname,lastname,username,password,email) VALUES ('".$first."','".$last."','".$user."','".$pass."','".$mail."');";
Thank you for answering,
DeleteI changed the thing that you mentioned,nothing happend.I still try to submit my data, but again there is no new record in my database.
Check out your database table fields similar as "firstname,lastname,username,password,email".
DeleteThanks a lot!! you were right, I had a minor spelling mistake in the email field and I didn't even notice it when I was checking it due to the frustration.I also have a second question about the login page.This message appears to directly when I'm accessing the page"Sorry, there is no username with the specified password.Try again",do you have any ideas?
DeleteThank you again!
Thanks, this code was very useful...
ReplyDeleteThanks a lot
ReplyDeletehi are you there MR.Anil gupta?
ReplyDeletecan you add header?
ReplyDeleteWhich header you want?
Deletehey how and where i save this table in 1st point
ReplyDeleteGo into "phpmyadmin", create database called "mydata".
DeleteAfter the click on SQL tab and paste the 1st point code and click on "Go" button. Your "User" table will get created
As I am a beginner in php so don't know much and want to make a login form in php
ReplyDeleteso please let me know how to save this table
error is coming while compiling login.php
ReplyDeleteSCREAM: Error suppression ignored for
( ! ) Notice: Undefined index: username in C:\wamp\www\login.php on line 4
Call Stack
# Time Memory Function Location
1 0.2400 368896 {main}( ) ..\login.php:0
Hey sorry for the previous comment
ReplyDeleteit is now working well
thank you so much
:)
Hello i have done everything as posted but i still get this message:
ReplyDeleteWarning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at /srv/disk3/1447904/www/racer.co.nf/login.php:1) in /srv/disk3/1447904/www/racer.co.nf/login.php on line 2
Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /srv/disk3/1447904/www/racer.co.nf/login.php:1) in /srv/disk3/1447904/www/racer.co.nf/login.php on line 2
Warning: Cannot modify header information - headers already sent by (output started at /srv/disk3/1447904/www/racer.co.nf/login.php:1) in /srv/disk3/1447904/www/racer.co.nf/login.php on line 31
why is this? (ps thank you so much)
how do i display the user who is logged in? and put it on a page?
ReplyDeleteCan you please elaborate exactly what you need?
Delete1- Number of user online or
2- Current user online.
number of users online
Deletehey how do i make a button 'register' in the form so as admin get a mail about this registration
ReplyDeleteIn signup page after clicking on submit just call mail() function which contain user filled details.
DeleteHere is a post for mail() function in Php.
Sending Mail in Php
i keep getting this message when i run this code:
ReplyDeleteWarning: mysql_num_rows() expects parameter 1 to be resource, boolean given in /srv/disk3/1447904/www/racer.co.nf/signup.php on line 12
Hi, after register when i am going to login browser send me a error
ReplyDeleteWarning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at H:\PROJECT\xampplite\htdocs\log_test\login.php:1) in H:\PROJECT\xampplite\htdocs\log_test\login.php on line 2
Warning: Cannot modify header information - headers already sent by (output started at H:\PROJECT\xampplite\htdocs\log_test\login.php:1) in H:\PROJECT\xampplite\htdocs\log_test\login.php on line 31
Please help me. I am new in php.
I think you have used "session_start()" twice in the page.
Deleteif you have included "session_start()" in main header then don't write it on login.php page or any other content page, because header will automatically included in all pages.
Thanks Anil Gupta for ur reply. After removing "session_start()"
Deleteit warned me
Warning: Cannot modify header information - headers already sent by (output started at H:\PROJECT\xampplite\htdocs\log_test\login.php:1) in H:\PROJECT\xampplite\htdocs\log_test\login.php on line 30.
Plz help me.
Can you show me your login.php code?
Delete1st part
Delete<?php
include("config.php"); //including config.php in our file
$username = $_POST["username"]; //Storing username in $username variable.
$password = $_POST["password"]; //Storing password in $password variable.
$match = "select id from $table where username = '".$_POST['username']."'
and password = '".$_POST['password']."';";
$qry = mysql_query($match);
$num_rows = mysql_num_rows($qry);
if ($num_rows <= 0) {
echo "Sorry, there is no username $username with the specified password.";
echo "Try again";
exit;
2nd part
Delete} else {
$_SESSION['user']= $_POST["username"];
header("location:admin.php");
// It is the page where you want to redirect user after login.
}
?>
Write at the beginning of your file and check.
DeleteBro.. i'v write full login.php part1 & part2. plz check the error.
DeleteIt save data in database, check username & password but dont login. it called error in line 31 which is
" header("location:admin.php"); ".
Make sure that "session_start()" is first line on your page.
Deleteplease ensure that there is nothing before session_start() command. Even a white space before the session_start() command will generate this warning message.
Deletesir i have same problem...plz help me what is should do...i have this error
DeleteWarning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\working\config.php:2) in C:\xampp\htdocs\working\login.php on line 28..
My email is: [email protected]
HI,
ReplyDeletePlease, PLEASE do not publish tutorials, where anything goes to database without being sanitized. SQL Injection all the way.
Thanks man for your comment, but this tutorial is for beginners who face difficulties during creation of their first login form.
DeleteI have also created tutorial in my blog for preventing SQL INJECTION. Here is the link of that.
Preventing SQL Injection
It's great that there is a tutorial for that too. But why leave the most important part away from the beginners? As information security is really a key part of every web application and therefore that's a first thing to learn before connecting anything to a DB
DeleteHi man, thanks for sharing this.
ReplyDeleteThank you very much! It's so helping me! But I think there's a fatal error on signup.php
ReplyDeleteyou can't use HTML tag ini PHP file unless you use echo ini it, even if I use it there will be a lot of problems following it. So I create 2 file named signup.php and signup.htm where I fill the signup.php with the PHP tags and the htm one with HTML tags and I add the code in signup.htm with include("signup.php");
I hope it will help.
Your teaching procedure is very very good I have learnt a log please keep continue to do more for us
ReplyDeletethe if statements are not working :(
ReplyDeleteI *really* hate tutorials like this being around on the web. It is just irresponsible to keep it around. The fact that it is aimed at beginners is even worse and certainly not an excuse. Beginners have no idea you give them vulnerable code.
ReplyDeleteWhen quickly glancing at the code I can see the following (without even digging deep into the code) :
- It uses a deprecated database API (when you wrote this it wasn't, but at the time there were already better alternatives around).
- It is vulnerable to SQL injection attacks
- It stores plain text passwords
- It is vulnerable to XSS attacks
Having resources like this around is just a proper dick move and is the #1 reason there are soo many vulnerable applications out there in the wild. People who are looking for information on how to create a login with PHP have no idea what is wrong with the above tutorial and implement it without knowing their application is wide open for attackers!
Just look at all the comments on here and even on Stack Overflow (http://stackoverflow.com/questions/17907822/php-login-error).
So I ask you: please take your responsibility and either take this tutorial down, add a big fat banner stating this should *never* be used in production because it contains huge security holes or fix all the issues in the code.
If for whatever reason you need / want help fixing the issues in the code or want to rewrite the entire thing and you need guidance you may contact me at my nickname @php.net. But whatever you choose this tutorial in its current state should simply not exist.