Session variables are used to store individual client’s information on the web server for later use, as a web server does not know which client’s request to be respond because HTTP address does not maintain state.
This tutorial enables you to create sessions in PHP via Login form and web server respond according to his/her request.
To Start a PHP Session:
<?php
session_start();
// Do Something
?>
To Store values in PHP Session variable:
<?php
session_start();
// Store Session Data
$_SESSION['login_user']= $username; // Initializing Session with value of PHP Variable
To Read values of PHP Session variable:
<?php
session_start();
// Store Session Data
$_SESSION['login_user']= $username; // Initializing Session with value of PHP Variable
echo $_SESSION['login_user'];
To Unset or Destroy a PHP Session:
<?php
session_destroy(); // Is Used To Destroy All Sessions
//Or
if(isset($_SESSION['id']))
unset($_SESSION['id']); //Is Used To Destroy Specified Session
In our example, we have a login form when user fills up required fields and press login button, a session will be created on server which assigns him a unique ID and stores user information for later use.
Watch out live demo or download the given codes to use it.
Recommended Products to create login forms.
1. Advance user registration and login scriptIt is a simple login and registration system is totally based on core PHP. This script fulfills all the basic to advance level login needs that a coder or a developer usually.
Buy Now
2. Advanced Security – PHP Register/LoginAdvanced Security is user registration/login system written in pure PHP. It is designed to provide very high-security level of any part of your system.
Buy Now
3.PHP AJAX Login & Register Form with SocialFlux – Clean, fast and very easy to customize with an elegant design. Useful – Can be integrated in every website or page in a few minutes, simple and fast.
Buy Now
4. AJAX User Registration and Login with CookieLet your users create accounts and login to your site with this script. Every request is made through ajax, which makes for a very easy user interaction with the site.
Buy Now
Complete HTML and PHP codes are given below.
PHP File: index.php
Given below code creates an HTML login form.
<?php
include('login.php'); // Includes Login Script
if(isset($_SESSION['login_user'])){
header("location: profile.php");
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Login Form in PHP with Session</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="main">
<h1>PHP Login Session Example</h1>
<div id="login">
<h2>Login Form</h2>
<form action="" method="post">
<label>UserName :</label>
<input id="name" name="username" placeholder="username" type="text">
<label>Password :</label>
<input id="password" name="password" placeholder="**********" type="password">
<input name="submit" type="submit" value=" Login ">
<span><?php echo $error; ?></span>
</form>
</div>
</div>
</body>
</html>
PHP File: login.php
Consists of login script in which PHP session is intialized.
<?php
session_start(); // Starting Session
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
}
else
{
// Define $username and $password
$username=$_POST['username'];
$password=$_POST['password'];
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect("localhost", "root", "");
// To protect MySQL injection for Security purpose
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
// Selecting Database
$db = mysql_select_db("company", $connection);
// SQL query to fetch information of registerd users and finds user match.
$query = mysql_query("select * from login where password='$password' AND username='$username'", $connection);
$rows = mysql_num_rows($query);
if ($rows == 1) {
$_SESSION['login_user']=$username; // Initializing Session
header("location: profile.php"); // Redirecting To Other Page
} else {
$error = "Username or Password is invalid";
}
mysql_close($connection); // Closing Connection
}
}
?>
PHP File: profile.php
It is the redirected page on successful login.
<?php
include('session.php');
?>
<!DOCTYPE html>
<html>
<head>
<title>Your Home Page</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="profile">
<b id="welcome">Welcome : <i><?php echo $login_session; ?></i></b>
<b id="logout"><a href="logout.php">Log Out</a></b>
</div>
</body>
</html>
PHP File: session.php
This page, fetches complete information of the logged in user.
<?php
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect("localhost", "root", "");
// Selecting Database
$db = mysql_select_db("company", $connection);
session_start();// Starting Session
// Storing Session
$user_check=$_SESSION['login_user'];
// SQL Query To Fetch Complete Information Of User
$ses_sql=mysql_query("select username from login where username='$user_check'", $connection);
$row = mysql_fetch_assoc($ses_sql);
$login_session =$row['username'];
if(!isset($login_session)){
mysql_close($connection); // Closing Connection
header('Location: index.php'); // Redirecting To Home Page
}
?>
PHP File: logout.php
To destroy all the sessions and redirecting to home page.
<?php
session_start();
if(session_destroy()) // Destroying All Sessions
{
header("Location: index.php"); // Redirecting To Home Page
}
?>
My SQL Code Segment:
To create database and table, execute following codes in your My SQL .
CREATE DATABASE company;
CREATE TABLE login(
id int(10) NOT NULL AUTO_INCREMENT,
username varchar(255) NOT NULL,
password varchar(255) NOT NULL,
PRIMARY KEY (id)
)
CSS File: style.css
Styling HTML elements.
@import http://fonts.googleapis.com/css?family=Raleway;
/*----------------------------------------------
CSS Settings For HTML Div ExactCenter
------------------------------------------------*/
#main {
width:960px;
margin:50px auto;
font-family:raleway
}
span {
color:red
}
h2 {
background-color:#FEFFED;
text-align:center;
border-radius:10px 10px 0 0;
margin:-10px -40px;
padding:15px
}
hr {
border:0;
border-bottom:1px solid #ccc;
margin:10px -40px;
margin-bottom:30px
}
#login {
width:300px;
float:left;
border-radius:10px;
font-family:raleway;
border:2px solid #ccc;
padding:10px 40px 25px;
margin-top:70px
}
input[type=text],input[type=password] {
width:99.5%;
padding:10px;
margin-top:8px;
border:1px solid #ccc;
padding-left:5px;
font-size:16px;
font-family:raleway
}
input[type=submit] {
width:100%;
background-color:#FFBC00;
color:#fff;
border:2px solid #FFCB00;
padding:10px;
font-size:20px;
cursor:pointer;
border-radius:5px;
margin-bottom:15px
}
#profile {
padding:50px;
border:1px dashed grey;
font-size:20px;
background-color:#DCE6F7
}
#logout {
float:right;
padding:5px;
border:dashed 1px gray
}
a {
text-decoration:none;
color:#6495ed
}
i {
color:#6495ed
}
Conclusion:
Through Login/Logout form it becomes easy to deal with sessions in PHP. Hope you like it, keep reading our other blogs.
352 Replies to “PHP Login Form with Sessions”
currently studying your tutorial, the reference to the sheet style is wrong ( or the name form_value.css is ) you have to make the change to see the page stylized
Hey Ahemkei!
We sincerely apologize for this inconvenience. Now, we have updated our codes and it’s reference.
Always feel free to use FormGet in future too. Your suggestions & feedback will be always appreciated.
Thanks & Regards,
FormGet.com
You can also join us on :
facebook : https://www.facebook.com/FormGet?ref_type=bookmark
twitter : https://twitter.com/hashtag/formget
google plus : https://plus.google.com/+Formget
Could put a tutorial on how to create a registration form together with the login and log out form
Can you kindly let me know how to get the login.sql fille
hello ,
it’s not working i need your help
Parse error: syntax error, unexpected T_STRING, expecting ‘,’ or ‘;’ in C:AppServwwwlogin.php on line 1522
how can i fix it
Hi Baskal,
I guess there is a syntax error at end of line no. 1522, please make sure complete the line with “;”
All the best !
Regards,
Ajmal
Hey guys i was wondering if somebody could help me to set up my database . Apparently Im doing something wrong. i´m just getting crazy trying to figure it out. Please help!
Hi Josefo
Thanks for reading this blog you can setup database by following steps
1) Go to http://localhost/phpmyadmin
2) Then create new database “company”
3) Import login.sql file which you will find in downloaded project’s folder
Hi admin,
Could you please tell me how to connect dreamweaver to web server. I have copied the data from your site and paste it in dreamweaver but if i double click the file it’s not working.
I am new for this php and all those things. So, kindly please anyone help me out for this problem.?
Thanks in advance,
Kumaresan S
Hi
I have copied your script straight to my server and changed the DB username from “root” , “”
to my own details for login
I have the DB “company” and the tables from your sql file imported, everything looks fine until I attempt to login, no matter what I use, alex, fugo, formget etc it returns Username or Password is invalid
Please help
Running windows &
IIS 7.5
PHP 5.3
Mysql
create DataBase in your table which will be fetched by your code.
very nice article dear
Thanks.
Works like a charm 😀
Thanks. maybe this code can help me 🙂
Great tutorial. Helped me a lot 🙂
i run your sample code sent into my email but I cant run the php files. It does not view the result or show the php code as text form as it is
Hello Tarun mukherjee
First unzip downloaded file and copy it on your local server
if you are using wamp then copy here
C:/wamp/www
for xamp
C:/xampp/htdocs
Do the following steps for database setup
1) Go to http://localhost/phpmyadmin
2) Then create new database “company”
3) Import login.sql file which you will find in downloaded project’s folder
Now open your browser and run index.php
http://localhost/login-form-php_download/index.php
great very simple and helping
NICE very helpful thanks a lot…………
Thanks for your appreciation .!
Keep reading our other blog posts :
https://www.formget.com/blog/
my code arent working that the error message i got.
I Was just wondering if someone could make me with a php script that works with this to register for a account?
You guys er really encouraging us keep it up i personally appreciate you all bye for now . . .
Very nice article. it is working properly.
Thank you
THANKS you have givin important knowledge very easy way
Hello to every body, it’s my first go to see of this website; this weblog consists of amazing and genuinely fine information in support of visitors.
Hello E & Omissions..
Thank you so much for your appreciation…!
Keep reading our other blog posts.. for getting more coding tricks..
Regards,
FormGet Team
can you provide a newer code using mysqli instead of mysql
please
thank you before
Thanks man 🙂
Appreciate your response…!
Keep reading our other blog posts for getting more coding tricks.
Thanks & Regards,
FormGet Team.
Join Us On
Facebook : https://www.facebook.com/FormGet
Twitter : https://twitter.com/FormGetcom
Google Plus : https://plus.google.com/+Formget
Why the password i enter (Eg: alex or ALEX) still can login by using your script?…in your demo only password (Eg: alex) can login…
Hello Kabuto,
First you need to store login details in your database.
Depending upon it , you will be able to login , and your script will work.
Regards,
FormGet Team
“Username or Password is invalid”
I have stored the login details in the database and I still get this error. Any clue?
Make sure that you have created the database as “Company” , table as “login” ,
column one as “id” , two as “username” and third as “password”.
hello admin i created the database named “company” and Table “login”
include 3 fields “id” ” username” ” password”
But the same error occurs again
“INVALID USER NAME AND PASSWORD”
Kindly help me how to solve this problem. Thanks in advance
Make sure that you have stored some data into the table. Like username as alex and password 123.
And try to login it with same detail, but before login check whether data is inserted into database or not.
Thank you very much.
very use full to me.
Hello Asbar,
That sounds really great ! Keep reading our other blog posts for getting more coding tricks.
Checkout new blog posts now : https://www.formget.com/blog/
Regards,
FormGet Team
Great tutorial, it’s helped me a lot!
I do have a beginner’s question, however.
I can’t seem to figure out how to pull and show the rest of my user’s database. For instance, in my database, I not only have a user name, but also their name, age, location etc…
I would like to display it all respectively, once each user has logged in. Could you tell me how to do that?
Any help would be appreciated. Thank you.
Hai sir i use ur code but
this warning error is displaying
Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in 24 line
what can i do. pls help me
Hello Muthu,
This is because , of database issue. Remember you need to create a database naming ‘company’ and table as ‘login’ with the column as id , username and password.
That will work fine.
Regards,
FormGet Team.
I changed the
if ($rows > 0) {
and it worked
session did not working.. plz help
Hello Nitesh,
Could you please let me know that what error you are getting while executing the code, so that I can help you out.
Thanks & Regards,
FormGet Team.
Nice information
thank you
Glad to have a reader like you !
Your words matters a lot for us.
Thanks & Regards,
FormGet Team.
I had same error message as Ebenezer.
In my case, it has been caused within login.php by:
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
Once I marked it as comment my access worked. However now we have the issue with the “open door” for sql-injection ….
// $username = mysql_real_escape_string($username);
// $password = mysql_real_escape_string($password);
Maybe this hint helps to find workaround.
Place the localhost connection before that :
//Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect(“localhost”, “root”, “”);
// To protect MySQL injection for Security purpose
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
Hope it will work for you.
I copied the code,saved it as the said file extensions,but this always happens whenever I type in the correct password.
Fatal error: Call to undefined function mysql_connect() in C:\ApacheServer\htdocs\login.php on line 14
Very cool, this is exactly what I was looking for?! I just made a rather lame login page yesterday without sessions etc and this helps me get to the next level. Sorry you will get lots of questions that are a bit out of scope- problems with mysql, problems with making sure they are using a webserver to serve up the page rather than opening it directly with a browser, windows paths etc. I’m on a mac and this was ridiculously easy to setup.
Thank you!
Ross
In Login.php, you are using mysql_real_escape_string before establishing a connection to the db.
From the manual:
Note:
A MySQL connection is required before using mysql_real_escape_string() otherwise an error of level E_WARNING is generated, and FALSE is returned. If link_identifier isn’t defined, the last MySQL connection is used.
http://php.net/manual/en/function.mysql-real-escape-string.php
The required changes has been done !
Thank you so much for intimating us about this.
Regards,
FormGet Team.
great job .nice code very neat and clean.for beginners thats the best way to learn form handling with php .i would like to see some validation on form data.
Hello Pankaj,
Thankyou so much for such a wonderful appreciation !
To apply validations in form fields , kindly followup this post : https://www.formget.com/php-contact-form/
Hope that will help you for that.
Regards,
FormGet Team.
Thanks for this code.Its great help for me .I was searching for code help like this….Once again thanks..
Hello Mamta,
That sounds really great ! Keep reading our other blog posts for getting more coding tricks.
Regards,
FormGet Team
Join Us On
Facebook : https://www.facebook.com/FormGet
Twitter : https://twitter.com/FormGetcom
Google Plus : https://plus.google.com/+Formget
thak you for the code.please help me to solve the error
Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in C:\wamp\www\shinu\login.php on line 24
Hello Shiu,
This is because , of database issue. Remember you need to create a database naming ‘company’ and table as ‘login’ with the column as id , username and password.
That will work fine.
Regards,
FormGet Team.
thanks for your good knowledge
Pleased with your response !
Keep reading our other blog posts for more coding tricks and knowledge.
Regards,
FormGet Team.
Join Us On
Facebook : https://www.facebook.com/FormGet
Twitter : https://twitter.com/FormGetcom
Google Plus : https://plus.google.com/+Formget
thanks sir your hellp me in website
Hello Vikram,
Pleased with your response. Keep following our latest posts for coding tricks and knowledge.’
Regards,
FormGet Team.
Hey I love this code. It works for me but I have two issues and one thing that I need for it. When ever I reach the log in page the sever credentials (root & password) are in the input fields. The server I’m using is xampp. Once I click in the fields and delete the user name root the password disappears and placeholder in the form username and password that I have in the code now appears. The other issue that I have is after logging out and it goes to the goodbye page if I should click the back button the page goes back to the login page (and of course root and the password are shown) but once you enter the username and password and click login it does nothing. To resolve that I made the goodbye page redirect to my homepage and not the login page. Even though that solved it I feel that the issue may affect something else. An addition that I would want for my user login is to have them go to individual pages. I’m building a photography site and want clients to be able to see their photos and be able to select which photo they want printed. So when a specific user logs in they are redirected to their profile page that only they have access to. Do I in the php that check the login credentials add multiple if statements for different users to redirect them to specific pages or what. So that this was a long posted question.
I was able to research the issue and sorted out the issue. The problem with the input fields being filled was a browser issue, so i placed a code to prevent that.
Respected Sir…
I found your tutorial very helpfull…
how can i create a feed back system..like yours comments page. i need such a page for my website.
Other think that i wanna mention is how to use bootstrap in website.
Regards
Awal Khan (Pakistan)
Hello Awal,
Right now we do not have any such tutorial , but i will let you know in future when we will create any.
Anyways thanks for reading the post and liking it.
Regards,
FormGet Team.
Respected Sir,
Is it possible to create an admin panel in a website, in which various interfaces are provided to end users. so they can publish their data easily..
for example a school website.. in which a news are announced in notice board..
I want to know, how to provide interface to end users and in which he/she posted the news which is then appeared in notice board page of site…
it is requested form yours that:
please refer me a link or some meaningful arguments about such system.
All the friends are requested that please help me in this regard..
Regards
Awal Khan
Pakistan
heey its very usefull for me thanks. But i want to ask you how to block the user if you was login you can’t go acces the login page? Thanks
Hi… Thank you for this great tutorial.. Can you please post the tutorial of uploading image and save it in a local folder?
Hello Divya,
Pleased with your response.
Here is the link where you will find number of tutorials for image upload :
https://www.formget.com/?s=upload+image
Hope I have helped you.
Regards,
FormGet Team.
Good Tutorial dear. Keep it up.
How to extend this example to destroy the session after some specific interval of time ?
thanks.
Hello Khan,
Use this code to destroy session and to remove all session variables.
// remove all session variables
session_unset();
// destroy the session
session_destroy();
Hope that will help you.
Regards,
FormGet Team.
Hello,
That sounds really great ! Keep reading our other blog posts for getting more coding tricks.
Catch up new posts from here
Regards,
FormGet Team
Hey Amin
I am trying to develop A database window application,I have been using help from here…Thanks.But i only have one problem,I dont know how to convert Mysql and php into an executable standalone app..Please help ASAP as i am getting close to my deadline.
I will be glad if u help.
Why this code in my case wont work with second user . My first user works but when i add second user username and password :: Username or Password is invalid? Is this some issue.
Hello MIlos,
Thank you so much for reading the post.
I have checked it at my end and found it to be working fine.
Let me know if any doubt persists.
Regards,
FormGet Team.
This is my little changed login , because of db fields>>> Can u see something wrong
O stupid sorry when I edited I confused $username and $password, and for test I enter same username and pass
for the first one now is corrected.
Thanks nice work!
Thanx Team Formget U Guys Doing Best
How to turn off usrname and password autocomplete?
You article is the bomb…I wish i could pay for every second i spent reading this
very good and easy undestanding login code thank you
no my web site but required domain name foe website
thanks good by
this is very nice
it shows the warning as mysql_real_escape_string access denied using password no how to resolve this error
after logging it is not displaying profile page. what could be the reason?
regards
nitesh
i have know php
i want to make logstic registration form
plz send me code kindly
Hello 🙂
I have copied your script straight to my server and changed the DB username from “root” , “”
to my own details for login
I have the DB “company” and the tables from your sql file imported, everything looks fine until I attempt to login, no matter what I use, alex, fugo, formget etc it returns Username or Password is invalid
Please help
very informative..thanks
Lovely clean look to your site and form. However, rooting through your code I saw some issues:
mysql_* functions: deprecated. You should use mysqli or PDO prepared statements and bind values/ parameters.
passwords: being stored as plaintext. They should always be stored as a hashed value. Newer versions of PHP use the password_hash() and password_verify() functions.
css: absolute values throughout. Difficult to work with absolute values like pixels for certain dimensions if developing a responsive form. Consider using % and rem.
Hi! I used all of your sample code and used the SQL, so therefore I have created a company database and login table. However, when I hit submit, it just stays on the same page and does nothing? I’ve tried changing the redirect page but still nothing. I’ve had this with other samples from different sites too
I’m having the same issue and cannot figure it out
Hello Jess
Thanks for sharing your problem with us.
First unzip downloaded file and copy it on your local server
if you are using wamp then copy here
C:/wamp/www
for xamp
C:/xampp/htdocs
Do the following steps for database setup
1) Go to http://localhost/phpmyadmin
2) Then create new database “company”
3) Import login.sql file which you will find in downloaded project’s folder
Now open your browser and run index.php
http://localhost/login-form-php_download/index.php
Insert username-formget and password-formget or username-fugo and password-fugo if you want to make your own username and password please insert first it on company database’s login table.
Thanks & Regards,
FormGet Team.
This paragraph will help the internet users for
creating new weblog or even a weblog from start to end.
so useful……i dont know about thae php.now i learn little bit.
thanks a lot.. it helps me a lot..
Isnt there supposed to be an on click code? For the login button?
session. php file must be included in evry page of my site to remain log in the site?
Warning: session_start() [function.session-start]: Cannot send session cache limiter – headers already sent (output started at C:\xampp\htdocs\prac\index.php:2) in C:\xampp\htdocs\prac\login.php on line 2
Hello cyden
Thanks for sharing your problem with us.
Write ob_start() before session_start() statement.
Look at below code for solutions.
ob_start();
This function will turn output buffering on. While output buffering is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer
Thanks & Regards,
FormGet Team.
It is very nice, clear code and saving my time. it works well.
Thank you. Thank you…
Hello Pangan
Thanks for sharing your problem with us.
Write ob_start() before session_start() statement.
Look at below code for solutions.
< ?php @ob_start(); session_start(); ?>
ob_start();
This function will turn output buffering on. While output buffering is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer
Thanks & Regards,
FormGet Team.
thank you
this is good for beginners i really like this work good man keep it up dear.
Harry!
you must enter user name and password in database record then try to log in
your post and website is great but would appreciate if you could update the code to sqli or pdo format, as sql will become invalid
i m new in php, your article is very intuitive, i adapted the code to run with postgres, it work very fine, thx e lot.
I have created the login form but when submit, it just gives me a page of the above php code.
You are doing such a great work.
Your tutorial is helpful for me.
I want to ask you that is that possible that if i logged in and go to profile age then login page never open till i am logged in.
I mean to say that after login and go to profile.php if i opened login.php then it will redirect to profile.php
Thank you.
I enter username & password but not redirecting of profile page.. what to do????????
I’m having the same problem. Any idea how to fix it?
thanks for useful site,it’s okaaaaayyy.
but when i run codes;
error of The mysql extension is deprecated and will be removed in the future
Merry Christmas and a hapy new year.
Thankyou..:)
Hi, how can I show the corresponding data of each user and ONLY his own data registered on db? I mean, I’d like the user to see only his own registers when a select is performed.
Hello Madson,
Thanks for reading up the post.
Follow up this post that will help you to do what you want : https://www.formget.com/read-mysql-data-using-php/
Let me know if you need any further help.
Regards,
FormGet Team.
Ya, this simple queries are easy. But I have 2 tables (login and events) and I want the user from login table to display his own events from events table. I read something about INNER JOIN but it’s not working. Do I have to add any other id/key when the event is inserted?
here is my code:
Untitled Document
query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
$id = $row[‘id’];
echo “”;
echo “”;
echo “”.””;
echo “”.$row[‘event_name’].””;
echo “Local:”;
echo “”.$row[‘event_place’].””;
echo “Data:”;
echo “”.$row[‘event_date’].””;
echo “Hora:”;
echo “”.$row[‘event_time’].””;
echo “”;
echo “”;
echo “Vip Antecipado:”;
echo “”.$row[‘vip_ant’].””;
echo “Normal Antecipado:”;
echo “”.$row[‘normal_ant’].””;
echo “Vip no local:”;
echo “”.$row[‘vip_local’].””;
echo “Normal no local:”;
echo “”.$row[‘normal_local’].””;
echo “Mais informações:”;
echo “”.$row[‘obs’].””;
?>
<a href="excluir.php?id=”>Excluir
<?php
}
}else{
echo "Oops! Nenhum evento seu está cadastrado ou já foi realizado.";
echo "setTimeout(function(){
window.location.href=’user_panel.php’;
}, 3000);”;
}
echo “”;
echo “”;
$db_conn->close();
?>
I specified two fields (user and pass) in both tables, asking for the user to confirm his username (usuario) and pass (senha) while registering a new event.Then I’m trying to compare both on SELECT query.
But if I enter the user_panel.php with another username, this one is able to see the registered event of the first user.
$sql = “SELECT cad_eventos.*, login.usuario
FROM cad_eventos INNER JOIN login
ON cad_eventos.usuario = login.usuario”;
Hi,
For everyone using this code be aware that it uses outdated mysql_* queries. These should be replaced with mysqli_* queries or PDO (http://php.net/manual/en/intro.pdo.php).
-ifor
Hi! I’m having a problem, i found out that after you successfully log in and you are in the homepage, when you click the “BACK” button, it goes back to the login page, which is not very wise. it should still remain in the homepage. please help
Hi first of all thank you for this tutorial. i am using this script it was working in local server, but not working while i am put it into main server. please help me
excellent tutorial man! thank you so much
thier some error. i cant access the index.php
thanks for this.
I’ll right away take hold of your rss as I can not find your
email subscription hyperlink or newsletter service.
Do you have any? Kindly permit me recognise so that I may just subscribe.
Thanks.
Hello TBDP,
You can follow up this link to get in touch with all latest blog posts.
https://www.formget.com/blog/
Hope you will be benefited with that.
Thanks & Regards,
FormGet.com
thanks
hi sir can you please tell me php how to create login and signup use to MYSQL
Hi… this tutorial is awsome it wroks perfectly…. but i got a question..
if i want to logging as admin i want to show me admin form, but if i was a user logging it shows me the same admin form
¿How do i redirect to my userpage?
I think you should set up permissions for various user groups in your database
Thank you for the amazing code. But can you help me with one question.
can one login page fetch data from multiple tables. If yes.can you please help me with the code.
Thanks for uploading such a nice link.
I have done all the things,, all things are working properly and i logged in correctly,,,, when I logged out then i go back to login screen,,, this means that all sessions are destroyed .
But when i press browser’s back button then i go back to the user profile screen,,where i did not get user’s name otherwise all same.., its mean session does not destroyed correctly.??
Please clarify this,,,, I did this in your demo,,,that was working nice,,no such issue.
Please reply me by my email asap.
thanks
Hello. Where do I configure the database login username, password, host etc? I have webhost, so localhost won’t work. Thanks for answers 🙂
thanks its working..and i have done it through your helping.
great help by you to me , it means alot to me. thanks again.
keep posted.
thanks you make my project more easier.
fekadu(africa,Ethiopia)!
i have try your ‘lesson’ above
but in my cpanel i try to configure
where and when i must put the ‘page.html’ in case if
example:
– pageloginsuccess.html if login success, and
– pageerrorlogin.html if login error
i mean the comment of redirecting
thx before
Hey
Does the source code provided above allow me to create a functional php mysql login database?
i would pay for the download but im just a student and im doing this for my computer science work.
could you give any advice on how to create a safe php mysql database with log in a register that will be very difficult to hack in the hour i will be presenting the work?
Hi
i thanks! That helps me a lot!
Is it possible to create a cookie?
I want to save the log in page as “apple web app” on my screen. and i don’t want to write everytime the password…
best greats from germany
Lukas
Hello .
it is a good tutorial .. 🙂
By the way , I wanna ask if this coding will make the username appear at every pages of our website ?
i fixed this now,had to make a single modification. Now this is my problem.
Fatal error: Call to undefined function mysql_connect() in C:\ApacheServer\htdocs\login.php on line 14
Hi, I followed the code and made all the necessary changes but when I log in, the next page is blank. The url reads …/login.php but there is no action taken, it doesn’t take me to page profile.php.
And also, I do not understand how the below code comes into play in session.php in the msql query statement
username=’$user_check'”
Realized my mistake 🙂
I have completed your script and it works fine, but when I log out and then press the back button I get error message saying that the input from the login screen is not recognised. Please Help.
Could someone please explain the need for the session.php file?
For storing Session Variables, making sure the user is logged in. etc.
Thanks a lot dude….. it really helped me. thank you..!!!!
I search to google and then I know where’s the error of it.. It is lacking and here is the complete code. Thank you again 🙂 God Bless
logout.php
thanks. 🙂
thank you.very well work done at here.it’s simple to understand.
Thank you very much very helpfullll 🙂
I get the error: This webpage has a redirect loop
details say: Error code: ERR_TOO_MANY_REDIRECTS
idk, I just copied and pasted the code. Im using the lastest version of XAMPP
I just wanted to say a big big thank you for your code, it has helped me greatly. Thanks for sharing!
Kind regards
Gaza
Congratulations! just have a problem in CSS, the font did not load!
(@import http://fonts.googleapis.com/css?family=Raleway😉
help!
hi admin can you help me i copy ur code and i try but after i submit the data
this is the result,,
//This webpage has a redirect loop)
i dont have idea on how to solve this problem anyone can help me
maybe you didnt start the xampp or the localhost
it doesn’t work..
//This webpage has a redirect loop// —whats the meaning of this?
Make sure you have the right information in the session.php file
this code has been very helpfull. Can I get the full download
admin,
i got this error page
The webpage at http://localhost/php/package/index.php has resulted in too many redirects. Clearing your cookies for this site or allowing third-party cookies may fix the problem. If not, it is possibly a server configuration issue and not a problem with your computer.
any different website is there like w3shcools
Hi,
just i create a registration form and user login by using formget ,i would like ask how can get register username and password is used to login please help me dude
Hola,
Al ejecutar el programa tengo el siguiente error: Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in C:\xampp\htdocs\registration.php on line 84
You can also follow FormGet Mysqli tutorial. Mysqli is really easy to implement.
https://www.formget.com/php-mysqli-insert/
i currently try your tutorial. .as i finished it. .it is not really secured. .coz once you had loged in. you can back to the main or to the index without using log out form. therefore, others can used your account without registering.
?php
session_start();
if(!isset($_SESSION[‘id’]))
{
header(‘location: login.php’);
}
else
{
?> //it is using for in your header in page //login is page enter your page name here
// it is using on end of
This is very good example
very helpful example of php session thank you…
hot do i link this together?
nice!!!!!!
I am very happy of that demo because for learn php very our help it
thanks
how to create customer profile with login session??? the login session i use your login ……… plzzz i needed …..
plzzz reply my question……
Your tutorial is very helpfull..learnt alot from it
So about PHP 5.6 mysql_ …… is deprecated, so I change every mysql_ …. with mysqli, make table in database and connect successfully, but when I type my username and password it says: “Username or Password is invalid”. So I think in this code have some mistake, but I can’t understand what is..:
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysqli_real_escape_string($username);
$password = mysqli_real_escape_string($password);
// Selecting Database
$db = mysqli_select_db(“company”, $connection);
// SQL query to fetch information of registerd users and finds user match.
$query = mysqli_query(“select * from login where password=’$password’ AND username=’$username'”, $connection);
$rows = mysqli_num_rows($query);
if ($rows == 1) {
$_SESSION[‘login_user’]=$username; // Initializing Session
header(“location: profile.php”); // Redirecting To Other Page
} else {
$error = “Username or Password is invalid”;
}
You can also follow FormGet Mysqli tutorial. Mysqli is really easy to implement.
https://www.formget.com/php-mysqli-insert/
very very useful codes it gives accurate results..
nice post !!!!!!!!!!!!!!!!!!!!
Hi………
What is the use of session? And difference between session and normal login code?
Great Job Sir! Code really helped and worked smoothly.
But their is one problem i’m facing. The output isn’t coming the same as above.
In style.css file, “@import http://fonts.googleapis.com/css?family=Raleway;” is not able to import that googleapis’ code and the text in all headings and labels is appearing in ‘TIMES NEW ROMAN’ . Can’t figure it out the the error. Performed a number of changes with other fonts also but didn’t worked.
Please Help!
I would strongly recommend converting this to PDO (php 5.1) so you don’t have to worry about escaping anything out and the code is cleaner. bindParam should sanitize your data. I would also recommend using password_hash (php 5.5) and/or password_verify (php.5.5) because you should *never* store passwords in plain text. Always hash them.
By doing both of these your code is cleaner (e.g. your db connection info is stored in a singular place, making future changes trivial), uses the latest security, and doesn’t care which database back end you use.
With the help of your code I was able to make a SQLite version which uses PDO and password_hash (which, with PDO, doesn’t really mater what back-end you use with the exception of the create script I use). Here is some of it and I’m sure, with your skills, you can quickly slap the rest together as it’s pretty obvious.
Regardless, thanks for putting this page together!
/****** LOGIN.PHP CODE HERE ******/
require_once(‘config.php’);
session_start();
$error=”;
if (isset($_POST[‘submit’])) {
if (empty($_POST[‘username’]) || empty($_POST[‘password’])) {
$error = “Username or Password is invalid”;
}
else {
$username=$_POST[‘username’];
$password=$_POST[‘password’];
$db = new PDO($db_login);
$statement = $db->prepare(“SELECT * FROM Login WHERE Username = :username”);
$statement->bindParam(‘:username’, $username);
$statement->execute();
$row = $statement->fetchObject();
if (!empty($row)){
$hash = $row->Password;
$match = password_verify($password, $hash);
if($match == false) {
echo “Username / Password invalid.”;
} else {
$_SESSION[‘login_user’] = $username;
header(“location: profile.php”);
}
}
$row = null;
$statement = null;
$db = null;
}
}
/****** SESSION.PHP CODE HERE ******/
require_once(‘config.php’);
$db = new PDO($db_login);
session_start();
$user_check=$_SESSION[‘login_user’];
$statement = $db->prepare(“SELECT Username FROM Login WHERE Username = :username”);
$statement->bindParam(‘:username’, $user_check);
$statement->execute();
$row = $statement->fetchObject();
$login_session = $row->Username;
// Close everything, jut to be sure.
$row = null;
$statement = null;
$db = null;
if(!isset($login_session)) {
header(‘Location: login.php’);
}
/****** CONFIG.PHP CODE HERE ******/
date_default_timezone_set(‘America/Chicago’); // US – Central Time Zone
$db_login = “sqlite:Inventory.sqlite”; // Connection string here. If you change this, make sure to adjust the create.sql to match the appropriate schema.
Thanks a lot for sharing your code.
Regards
Neeraj
FormGet Team
Thanks a lot you made my day .. 😀
Nice blog very helpful It made Login/Logout form easy to deal with sessions in PHP
Can u do the code in PDO form please?? Everything works fine in this code but i want it PDO format.It would be great if you provide the link for PDO format!!
Thank u
All fine and good but you really shouldn’t promote the use of the old mysql extension. It is more than ten years old and PHP programmers need to learn how to use PDO or mysqli and prepared statements.
Would you like to submit a tutorial based mysqli for the users ?
Thank you for this code. My professor didn’t teach us how to use Session and many more and now he want us to create a simple website to Create a simple Dynamic website.
Thanks again.!
Thank you so much
Very helpful lesson for new php learner.
all things are well come.
Thank you very much for the reputable document above. I have one more question How to combine the above codes to appear in only one php file?
I am working in php , and your publishing is very userful to me and its too clearly i like this thank you
Hi,
If I try to visit a page which is protected by the session, I get this in the error_log:
PHP Notice: Undefined index: login_user in
Obviously it happens because ‘login_user’ isn’t defined because they’re aren’t logged in but is there a way to stop that?
Thanks
if(!isset($_SESSION[‘login_user’])) {
header(“Location: index.php”);
exit;
}
For me i need a complete/ comprehensive login and logout system (codes) that will help me to develop my own thing i.e system as am still a young php developer.
Hi, I’m wondering how do I retrieve & display data from database using this session? Thanks.
hi..
thanks for sharing the code for login page.. i follow your coding method and successfully login. but i have a problem when i click on log out. my log out does not function, it display a blank page, then i try it again, it still the current user name login. how to make it function?
Simply awesome.
sir ,
i copied all the codes that u r given in this blog i created db in wamp server also but while running the programs(all) iam getting the code asusual as i copied can u pls give me the suggestion to run this ,iam new learner of php in online
Awesome description about creating session and using session variables in PHP. Simple and Easy to Understand.
can u pls tel me how to execute this program iam new learner i copied all the code and created db in wamp server and imported login.php but iam not getting output ,the total code which i copied is executing while running pls help me to execute
Thank you very much
Danke schönnnnnnnnnnnnnnn. German
Faliminderit shummmmmmmmm. Albanian
sir, please send full project in php?ect name i
project name is Hotel management System
Very very very gooooodddd website….This is very helpful for me…
Very Nice system, it’s good code and security – it’s great system.
good luck man, you are a good man 🙂
Hi i saw your coding it can be work login or logout ……Thank u so much……
I get error at index.php line 4. It says “Parse error: syntax error, unexpected ‘if'”.
How to fix it? Thanks
Awesome.
Very Simple and straight forward.
Keep it up this work.
Thanks.
good script, thanks
Anyone knows why i get autofilled username and password with root.. i have disabled autofill in my browser
To stop autofill by robot you can follow our blog post. https://www.formget.com/disable-auto-complete-in-form-fields-jquery/
Good tutorial. However, I get a redirect loop error after i finished doing all steps. Can you please show me how to rectify this.
Thanks.
Hello mates, its great piece of writing concerning teachingand entirely
defined, keep it up all the time.
Hey admin it works fine, good job.
But how do i store other variables like email, rank, and so on?
Nevermind i figured it out change session.php to
Then use this sql code
— phpMyAdmin SQL Dump
— version 4.2.11
— http://www.phpmyadmin.net
—
— Host: 127.0.0.1
— Generation Time: Apr 25, 2015 at 07:51 PM
— Server version: 5.6.21
— PHP Version: 5.5.19
SET SQL_MODE = “NO_AUTO_VALUE_ON_ZERO”;
SET time_zone = “+00:00″;
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
—
— Database: `company`
—
— ——————————————————–
—
— Table structure for table `login`
—
CREATE TABLE IF NOT EXISTS `login` (
`id` int(10) NOT NULL,
`username` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`rank` varchar(255) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;
—
— Dumping data for table `login`
—
INSERT INTO `login` (`id`, `username`, `password`, `email`, `rank`) VALUES
(1, ‘SaintNic’, ‘Silver98’, ”, ‘Administrator’);
—
— Indexes for dumped tables
—
—
— Indexes for table `login`
—
ALTER TABLE `login`
ADD PRIMARY KEY (`id`);
—
— AUTO_INCREMENT for dumped tables
—
—
— AUTO_INCREMENT for table `login`
—
ALTER TABLE `login`
MODIFY `id` int(10) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=2;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
$connection = mysql_connect(“localhost”, “root”, “”);
$db = mysql_select_db(“test”, $connection);
session_start();
$user_check=$_SESSION[‘login_user’];
$ses_sql=mysql_query(“select username from login where username=’$user_check'”, $connection);
$user_data_sql=mysql_query(“select username, password, email, rank from login where username=’$user_check'”, $connection);
$row = mysql_fetch_assoc($ses_sql);
$output_data = mysql_fetch_assoc($user_data_sql);
$login_session =$row[‘username’];
$login_session_password =$output_data[‘password’];
$login_session_email =$output_data[’email’];
$login_session_rank =$output_data[‘rank’];
if(!isset($login_session)){
mysql_close($connection);
header(‘Location: ./index’);
}
thanks, your program is very good!
You can also add an ht access folder
Make a new folder called “.htaccess”
And put this code in it
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]
Or if you want to add a trailing slash at the end use this code
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+)/$ $1.php
RewriteRule ^([^/]+)/([^/]+)/$ /$1/$2.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/)$
RewriteRule (.*)$ /$1/ [R=301,L]
Now you don’t have to put the .php at the end of you files 🙂
Hi ,
This tuturial is very nice , just i show and currently i am studying your tutorial.
The example is great and works perfectly, would it be possible to get a tutorial from this to allow users of different access levels different restrictions when logging in such as admin functions and user functions?
Yea it’s very simple use the my sql table above in my previous comment
And change session.php to
$connection = mysql_connect(“localhost”, “root”, “”);
$db = mysql_select_db(“company”, $connection);
session_start();
$user_check=$_SESSION[‘login_user’];
$ses_sql=mysql_query(“select username from login where username=’$user_check’”, $connection);
$user_data_sql=mysql_query(“select username, password, email, rank from login where username=’$user_check’”, $connection);
$row = mysql_fetch_assoc($ses_sql);
$output_data = mysql_fetch_assoc($user_data_sql);
$login_session =$row[‘username’];
$login_session_password =$output_data[‘password’];
$login_session_email =$output_data[’email’];
$login_session_rank =$output_data[‘rank’];
if(!isset($login_session)){
mysql_close($connection);
header(‘Location: ./index’);
}
Then in your database create an account then put rank as 1 for user and 9 for administrative
Restrict pages only to administer put this code at the top make sure you include session.php first
if ($login_session_rank == “9”) {
} else {
header(“location: ./restricted.php”)
exit;
}
Then create a php file called restricted and make it say you have no access to view this page
I’ll use (?php, ?) As starting and ending brackets
what about if your an admin and you want stuff to be show for admins but not for users on a certain page
(?php
if ($login_session_rank == “9”) {
?)
Page content admin can see
(?php
}
?)
But that’s how I did the access levels and you can add more like moderator and etc.
i cant seem to get the example working it is saying that i have the following error
“Parse error: syntax error, unexpected T_STRING in /home/atreddenick/public_html/login_example/session.php on line 11”
and this is what i have on that line
“$user_data_sql=mysql_query(“select username, password, rank, from login where username=’$user_check’”, $connection);”
i have taken out the email part as it is not necessary for my example but i cant work out where i have gone wrong.
Any help would be great.
Thanks
What does your sql code look like ??
sometimes it’s the sql code
ilike for example if your sql looks like this for the login table
CREATE TABLE IF NOT EXISTS `login` (
`id` int(10) NOT NULL,
`username` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`rank` varchar(255) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;
and you do
“select username, password, rank”
you will get an error
because you can skip email so I would either delete the email field or put rank before email
If you want I can email you the script, I have made admin levels, remember me, and other cool functions, I even managed to create a mysqli, and a PDO Connection so if you want me to send the script to you email me at “[email protected]” put PHPLoginHelp as subject and ill email you back as soon as I can 🙂
What does your whole session.php code look like the whole file content ?
it is good tutorial..i am not a average student of php below average………but i can easily to understand the tutorial………its more help me
it is not clear once wamp server is loaded on my computer, and your directory ‘php_login_form’ is put in root director www. of wamp localhost…what to do next?
I mean how to connect with my own external web server and pass or create database for login from wamp server on my computer?
thanks
Damir
Can you help me. How to make login page when the user have different database. i have admin table and i have owner table.
Hi admin,
I am fed up with error…please may u help me out.
No matter what i type in user name and password fields, i am always getting Invalid login. My database has 3 fields (id, username, password)
Hey Neeraj,
Thanks a ton for the pseudo code. This saved my time.
Thanks a lot guys – easy, clear and clean!
Although, used prepared statements. E.g. for login.php (for anyone wondering):
[…]
$mysql_hostname = ‘localhost’;
$mysql_dbname = ‘db_name’;
$mysql_username = ‘root’;
$mysql_password = ‘123’;
$connection = new PDO(“mysql:host=$mysql_hostname;dbname=$mysql_dbname”, $mysql_username, $mysql_password);
$conn_statement = $connection->prepare(“SELECT username, password FROM account WHERE username = :username AND password = :password”);
$conn_statement->execute(array(‘:username’ => $username, ‘:password’ => $password));
$affected_rows = $conn_statement->rowCount();
if ($affected_rows == 1) {
$_SESSION[‘account_session’] = $username;
header(“location: ./template/account.php”);
}
else {
$error = “Given information is invalid!”;
}
$connection = null; //closing connection
Thank you very macho. It’s nice work
Hello,
I got a problem that it doesn’t want to execute the header command.
it just ignores it..
I have read some things but it’s still not really clear what i have to do..
Can u help me ? thanks !
i added this
header( “refresh:2;profile.php” );
echo ‘You’ll be redirected in about 2 secs. If not, click here.’;
when i click the link then it goes to profile.php, but then it doesn’t show the name of the user.
Hello Pieter,
Thank you so much for reading the post.
I have checked it at my end and found it to be working fine.
you should to add header( “refresh:2;profile.php” ); in both login and index file.
Let me know if any doubt persists.
Regards,
FormGet Team.
how could i put these codes in www director of wamp server p/s help me am new for web development..
Hello Yirgalem Mekuria.
First, create a folder name loginwithphp or any name and inside loginwithphp, create all files which are mentioned above, after
if you are using wamp then copy here
C:/wamp/www
for xamp
C:/xampp/htdocs
Do the following steps for database setup
1) Go to http://localhost/phpmyadmin
2) Then create new database “company”
3) Create a table name, login with above mentioned attributes and insert dummy data on it
Now open your browser and run index.php
http://localhost/login-form-php_download/index.php
Let me know if any doubt persists.
Regards,
FormGet Team.
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in D:\Hosting\5477578\html\vijayadasaru.net\test\login.php on line 24 this is the error message iam getting
Help?
Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in
public_html/Home/login.php on line 24
I’m not getting any emails and an error when resetting password:
Undefined variable: subject in C:xampphtdocsdemo2php_login_formpassword_reset.php on line 68
As instructed I have updated link to http://www.songuide.com in all corresponding files.
Uff…! Thank You sir for sharing this.
thanks.
works great.
🙂 😀
Just a warning, this is easily one of the most dangerous ways to handle password storage, and by using this technique as-is, you are putting the passwords of all of your users at risk.
It is worth nothing that this is an incredibly insecure way to handle logins. You should NEVER store a password in a database. The correct way to do this is by using a cryptographic hash to store the salted password in the database. Thus, if your database is compromised, you will not leak passwords for all of your users as so many companies have done recently. This is especially important as users may reuse these passwords on much more important and secure sites.
The correct way is:
Accept user password
Generate random salt
Hash password + salt
Store this hash and salt
Now, when someone attempts a login, you would take what they supply for their password, append the stored salt, hash it, and compare that to the stored hash in your database.
To anyone writing a tutorial, I implore you to please stop spreading dangerous and irresponsible practices. You have a duty to your users to have at least a modicum of understanding of security for their sake.
This is true, and to add to the alarm, it’s using mysql instead of mysqli or PDO. No tutorial using mysql instead of the latter should be really taken seriously at this point in the game since it’s been proven vulnerable and is now deprecated.
very awesome code
Hey, great page and worked first time and was very easy to understand.
I am guessing that if I include the code
Hey, great page and worked first time and was very easy to understand.
I am guessing that if I include the code
then it will make sure that the user is logged in and allowed to see it?
Its a good and clean code thanks very much
it is help full tutorial so i want to say tank you
but can you add something about how to check login password with registration password
Hello every one. Nice code admin but I’m having a problem with the login section it keeps bringing the error message and the database help me on auto increment
Very Nice 🙂
plz help.. how can i get the SQL.file
Hi,
admin i saw your tutorial demo and i liked it but its difficult form me to understand how do you prevent your page from going back or could you make an video tutorial please.
Thank you
thank you very much
What is the purpose of “id” in:
UserName :
Password :
is it really required to have that “id”?
what is the difference of “id” in “name”?
Thanks though I have my own login form with database still I really like this one simple and very understandable… Thank you so much
Great Job ! 🙂
Thanks, New knowledge for me
Frnz how can we link website code in cpanel to domain name.
why you have used the following code at the very starting of index.php ??
Hi,
Wonderful tutorial and thanks for your sharing.
I just have a question that: how to record the login time while successful log-in?
I tried to record the login time to another table (but in same database) after success log in. However did not work. Can anyone help me?
Thank you.
Rebecca
thank you so much
Warning:session_start(): Cannot send session cookie and cache limiter – header already sent (output started at C:\xammpplite\htdocs\project\login.php on line 2
“” on line 24
“” index.php on line 5
Hi Admin, thanks for the codes though I had a bit of a problem.
I copied all those codes, even made the database. Everything works perfectly.
Well not everything, when I press the logout button, which redirects to logout.php where the session gets cut off, instead of redirecting to index.php it just stays there. A white page, nothing. Nothing happens. Any ideas what caused it?
I need it for a project. Thank you so much sir
what is this thing i do not know and i have never use php before in my life and this language is great and easy and i will continue to lerning and i hope one day i will be master of thise language…
Thanks a lot…… 🙂 i want this code………….
Great code and worked fine in WAMP but when I uploaded it to my website host I encountered the same problem that several people on this page have already had: –
Warning: session_start(): Cannot send session cache limiter – headers already sent (output started at /home1/bespokew/public_html/admin/profile.php:2) in /home1/bespokew/public_html/admin/session.php on line 12
I followed your advise of putting ‘@ob_start();’ before ‘session_start();’ but the same error message keeps appearing. Please help.
I make HTML web on my computer desktop after that i installed xampp and xampp -> htdocs folder i make login php so, my question is that do i need to make index.php on it or not if so how about html that i created on desktop.that index.html also i have to move on xampp -> htdocs folder
Hey ya, i’m very glad to read your tutorial. And i’m it’s very helpfull for me :). Thanks for everyone doing this job, and sorry for my bad english :).
I am working on your example and i get this error.. i can’t find solution please please help….
“mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given in C:wampwwwaddscloudsession.php” on line 13
Hello,
Such error occurs usually when the mysqli_query hasn’t run properly.
Check whether your query is executed properly or does it contains anything or not. The problem may be with the connection, query or it may be with the tables.
So, make sure that your query must contain the same table name that you have created in your database. Also, check that the query contains the results.
Hello, i am having a problem where it opens the “500 Internal Server Error” upon sign in, could that be a result of changing the name of the table from the sql that you have above, if so, how would i fix this problem, thanks
Hi,
Use the same database name, table name and column name in query that you have created at your end. It would resolve your issue.
hi i like ur login pgm. its very nice. i have a little problem with mine.
i added more fields to database tables and i want it displayed. pls hw do i do it. i have tried all method but it doesn’t read the entire row iinformation to display in profile.php
i m having trouble with connecting html website with ,my spl
please tell me any ways so that i can connect them
In this way the session connection it’s very simple!
Grazie tante from Italy
thanks for the tutorial. pls can you help me i want to display full user info from my db row when user logs in. i added more fields to tthe table
Thanks for your loginpage
It’s real helpful to me
Hello all, here every one is sharing these know-how, therefore it’s nice to read this webpage,
and I used to visit this website all the time.
Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in /Applications/XAMPP/xamppfiles/htdocs/ezbz_4/login.php on line 22
This post is awesome. Really very helpful. (y)
How to check with session which user is logged in … ? if i want to access page i can’t … like if i am logged in as user1 and i hvae my view of my profile and someone else logged as user2 want to see my profile and he type in url .php?u=$username and my username which show my profil info is user1 … how to use session to see am i visiting that page or somebody else.. so if its me i get page with everything and if it is somebody else he gets page with some of my info?
thank you it is very informative 🙂
keep up
Works great, thank you to share!
Also, the css file produces a clean, nice, and easy interface.
Also, to make it responsive for mobile, don’t forget to add the below meta inside your head tags:
<meta name="viewport" content="width=device-width, initial-scale=1"
Am planning to prepare one project and need some help and suggestions.
Hi,
I have updated the terms for Mysqli, but no matter what i try to login with i got Username and Password is invalid as the result, even though it is corrected to the corrected table within the database. any help would be great.
thank you guys it help a lot .
Why in the session.php file do you check again if the user exists in the database? It’s a security problem or it’s just to retrieve user datas?
Thank you for your help, I hope you still answer to questions on this post 😛
Hi
Im trying to get the username of the logged in user displayed, i have implemented sessions but to no avail. Once the user logs in at first it displays the message you are logged in as “Eddy Kay” for instance, but once you click another link the username vanishes. Could you tell me what I am doing wrong please.
Here is the code below.
User_User.class.php
class User_User {
public function __construct(){
//start a session
session_start();
}
public function isLoggedIn(){
$sessionIsSet = isset( $_SESSION[‘username’]);
if ( $sessionIsSet ) {
$out = $_SESSION[‘username’];
} else {
$out = false;
}
return $out;
}
public function login () {
//set session variable [‘logged_in’] to true
$_SESSION[‘username’] = true;
}
public function logout () {
//set session variable [‘logged_in’] to false
$_SESSION[‘username’] = false;
}
}
User_Table.class.php
checkEmail( $email );
$this->checkUsername($username);
//encrypt password with MD5
$sql = “INSERT INTO users (email, firstname, lastname, username, password)
VALUES(?, ?, ?, ?, MD5(?))”;
$data= array( $email, $firstname, $lastname, $username, $password );
$this->makeStatement( $sql, $data );
}
private function checkEmail ($email) {
$sql = “SELECT email FROM users WHERE email = ?”;
$data = array( $email );
$this->makeStatement( $sql, $data );
$statement = $this->makeStatement( $sql, $data );
//if a user with that e-mail is found in database
if ( $statement->rowCount() === 1 ) {
//throw an exception > do NOT create new admin user
$e = new Exception(“Error: ‘$email’ already used!”);
throw $e;
}
}
private function checkUsername ($username) {
$sql = “SELECT username FROM users WHERE username = ?”;
$data = array( $username );
$this->makeStatement( $sql, $data );
$statement = $this->makeStatement( $sql, $data );
//if a user with that e-mail is found in database
if ( $statement->rowCount() === 1 ) {
//throw an exception > do NOT create new admin user
$e = new Exception(“Error: ‘$username’ already used!”);
throw $e;
}
}
public function checkCredentials ( $username, $password ){
$sql = “SELECT username FROM users
WHERE username = ? AND password = MD5(?)”;
$data = array($username, $password);
$statement = $this->makeStatement( $sql, $data );
if ( $statement->rowCount() === 1 ) {
$out = true;
} else {
$loginProblem = new Exception( “Username/Password incorrect” );
throw $loginProblem;
}
return $out;
}
public function getUserName($username)
{
$sql = “SELECT username FROM users WHERE username = ? “;
$data = array($username);
$statement = $this->makeStatement($sql, $data);
return $statement;
}
}
?>
login.php
checkCredentials( $username, $password );
$userTable->getUserName($username);
$user->login();
} catch ( Exception $e ) {
//login failed
}
//end of code changes
}
$loggingOut = isset ( $_POST[‘logout’] );
if ( $loggingOut ){
$user->logout();
}
if($user->isLoggedIn())
{
$view = include_once “views/logout-form-html.php”;
}
else
{
$view = include_once “views/login-form-html.php”;
}
return $view;
?>
login-form-html.php
<?php
return "
Login to access restricted area
Username
Password
“;
?>
logout-form-html.php
<?php
if (isset($username) === false )
{
$username = "";
}
return "
logged in as $username
“;
?>
Thank you.
Hello
Why you call two time redirect on profile.php header(“location: profile.php”); ?
One time in login.php, and second in index.php?
Regards
Alexander
i am studing how to make login form in php using session but i am getting an error stating ”
Object not found!
The requested URL was not found on this server. If you entered the URL manually please check your spelling and try again.
If you think this is a server error, please contact the webmaster.
Error 404
localhost
04-12-2015 14:09:52
Apache/2.2.14 (Win32) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l mod_autoindex_color PHP/5.3.1 mod_apreq2-20090110/2.7.1 mod_perl/2.0.4 Perl/v5.10.1
please advice..
Hi? I don’t think it might helped me out but frankly it gives me an idea. Thanks.
whenever i refer to my profile.page first it wont take me to index.page.. i dont know why its doing this, but this peace of code never works i think in any case.. any help please.
On loading index.php, browser displays that ” This web page has a redirect loop “, so how to overcome this problem ?
love you nice code thank you so much but need some changes to mysqli
Quality articles is the crucial to be a focus for the users
to visit the site, that’s what this web site is providing.
I was recommended this website by my cousin. I’m now not sure whether or not this put up is
written via him as no one else realize such distinct approximately my problem.
You are incredible! Thank you!
Thank you so much.. I wasted days to find how to create a login form. This worked. (y)
Keep up the good work!
Yes it works
helpful than i read b4…..thanks!
Nice program and self explanatory…All the best
This post will assist the internet people for building up new blog or even a weblog from
start to end.
Very nice code.it usefull for mi . i like the way its describe.
What’s up, every time i used to check webpage posts here early in the daylight, because i love to gain knowledge of more and more.
Good blog post. I definitely appreciate this website. Keep writing!
Iblog often and I truely appreciate your content. Your article has really peaked my interest.
I am going to bookmark your website and keep checking for new details about
once a week. I opted in for your RSS feed
too.
How can i start a new SESSION…
Eg: on my table have “Access Level”, how can i call that as a SESSION..?
Sir sql is not working showing error
Thanks for sharinjg your thoughts on php
login form. Regards
Making Same Please Help Me To Cpnfigure CSS And PHP Script On WAMP
Thanks a lot for this example, was of great use!
i need pdo login and registration form using php.
hey i just got this error
Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given
I am genuiinely grateful to the holder of this website who has hared this wonderful paragraph
at at this place.
Your session does not work coorectly. If both auser are loged in, and when you refresh the page of the first user (which loged in), the datas of the last user will overide the datas of the first one.
I programm a smiliar thing and have the same problem with the sessions.
This happens, cause php create every time the same session for ervery user and not a individual session like in java ee.
I hope you update your code with the correct solution.
Best Regards Alex from Germany
thanks Alex for the update. i will like to share my source code with you so you can have a look at it. if you will have the time pls notify me on my mail. maybe we can collaborate, cos i’m building something else now. thanks in advance
It will make me happy to see more of your codes, maybe we can create codes together as example
Greetings Alex
the code is really perfect. You made my day
Hi there all, here every onee is sharing these kinds of knowledge, so it’s pleasant to read this
website, annd I used to pay a quick visit this website everyday.
Excelente aporte, me sirvió.
¡Muchas gracias!
Thank you for all the help you guys. i had struggled for a login page for 2years until tiday
You guys are awesome, help me a lot in making those Login forms. Keep It Up. Be Happy
God Bless You
I’ve got error that says:
Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given
I tried to Google search for the possible solution to no avail. I tried to trap the error since it says that $query is a boolean:
if (false === $query) {
echo mysql_error();
}
The mysql_error is No database selected. Please help me and thanks a lot for the sample script.
Thank you very much it works perfectly
Thank You so much. This made my day. great job.
Wish The best for u you.
This design is incredible! You obviously know how to keep a reader entertained.
Between your wit and your videos, I was almost moved to start
my own blog (well, almost…HaHa!) Wonderful job.
I really loved what you had to say, and more than that, how you presented
it. Too cool!
Thank you for this little tutorial I have Learned so Much in using session and stripslashes.
Please can anyone help???? I tried it but my session is not login in to my redirected page rather its returning me back to the login form….help me ou
CREATE DATABASE company;
CREATE TABLE login(
id int(10) NOT NULL AUTO_INCREMENT,
username varchar(255) NOT NULL,
password varchar(255) NOT NULL,
PRIMARY KEY (id)
)
using it on xaamp my sql cmd
but the error is “#1046 – No database selected”
please help me figure it out
I have been checking out a few of your posts and i
can claim nice stuff. I will make sure to bookmark your site.
What a fantastic page. Thank you for your help 🙂
hello thank you so much for this code!!! really big help!!
Its so amazing to have this kind of work and those kind of people who shares this ideas 😀 good job bruuu this is the only source code ive done in an ease 🙂
Thank you sir! This is really helpfull for me to realise what the session really is. Have a nice one!
Thanx a lot it help the young designers like us..
Work excellent
Perfect.
Excellent tutorial.
I thank you.
There are many examples in NET, but yours was the only one that worked.
Congratulations
thank you sir,for giving this understanding code to us.
but iam getting the error is as below while redirecting to the login page to profile page
This page isn’t working
localhost redirected you too many times.
Try clearing your cookies.
ERR_TOO_MANY_REDIRECTS
Even though I did copy all codes correctly the login is not redirecting me to profile.php and shows blank screen.I did insert record in table login and used same while logging in.
whoah this blog is excellent i really like reading your posts.
Keep up the great work! You understand, many
persons are hunting round for this info, you can help them greatly.
hi
admin
thank you
every thing is ok but
username and password is invalid
i mean i don’t know please help me
i need username and password in login form
thanks
I love the efforts you have put in this, thank you for all the great articles.
Quality content is the main to attract the viewers to visit the web page, that’s
what this site is providing.
This article offers clear idea for the new users of blogging,
that actually how to do blogging and site-building.
hello, i need your help.
Fatal error: Uncaught Error: Call to undefined function mysql_connect() in /Applications/XAMPP/xamppfiles/htdocs/login.php:14 Stack trace: #0 /Applications/XAMPP/xamppfiles/htdocs/index.php(2): include() #1 {main} thrown in /Applications/XAMPP/xamppfiles/htdocs/login.php on line 14