Firstly, the PHP documentation has some excellent information on sessions. Secondly, you will need some way to store the credentials for each user of your website (e.g. a database). It is a good idea not to store passwords as human-readable, unencrypted plain text.
When storing passwords, you should use PHP's crypt() hashing function. This means that if any credentials are compromised, the passwords are not readily available. Most log-in systems will hash/crypt the password a user enters then compare the result to the hash in the storage system (e.g. database) for the corresponding username. If the hash of the entered password matches the
stored hash, the user has entered the correct password. You can use session variables to store information about the current state of the user - i.e. are they logged in or not, and if they are you can also store their unique user ID or any other information you need readily available. To start a PHP session, you need to call session_start() . Similarly, to destroy a session and its data, you
need to call session_destroy() (for example, when the user logs out): // Begin the session
session_start();
// Use session variables
$_SESSION['userid'] = $userid;
// E.g. find if the user is logged in
if($_SESSION['userid']) {
// Logged in
}
else {
// Not logged in
}
// Destroy the session
if($log_out)
session_destroy();
I would also recommend that you take a look at this. There's some good, easy to follow information on creating a simple log-in system there. Updated on July 1, 2020 by Neeraj Agarwal 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.
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">
<h2>PHP Login Session Example</h2>
<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
}
![How to use session in login form in php](/dist/images/loading.svg)
Conclusion: Through Login/Logout form it becomes easy to deal with sessions in PHP.
Hope you like it, keep reading our other blogs. 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 Reply Reply Could put a tutorial on how to create a registration form together with the login and log out form Reply Can you kindly let me know how to get the login.sql fille Reply
hello , it’s not working i need your help Reply Parse error: syntax error, unexpected T_STRING, expecting ‘,’ or ‘;’ in C:AppServwwwlogin.php on line 1522 how can i fix it Reply 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 Reply
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! Reply 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 Reply 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 Reply
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 Reply create DataBase in your table which will be fetched by your code. Reply
very nice article dear Reply Thanks. Works like a charm 😀 Reply Thanks. maybe this code can help me 🙂 Reply Great tutorial. Helped me a lot 🙂 Reply 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
Reply 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 Reply
-
great very simple and helping Reply NICE very helpful thanks a lot………… Reply Reply
my code arent working that the error message i got. Reply I Was just wondering if someone could make me with a php script that works with this to register for a account? Reply You guys er really encouraging us keep it up i personally appreciate you all bye for now . . . Reply Very nice article. it is working properly. Thank you Reply THANKS you have givin important knowledge very easy way Reply 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. Reply Hello E & Omissions.. Thank you so much for your
appreciation…! Keep reading our other blog posts.. for getting more coding tricks.. Regards, FormGet Team Reply can
you provide a newer code using mysqli instead of mysql please thank you before Reply
Thanks man 🙂 Reply Reply
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…
Reply 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 Reply
“Username or Password is invalid” I have stored the
login details in the database and I still get this error. Any clue? Reply Make sure that you have created the database as
“Company” , table as “login” , column one as “id” , two as “username” and third as “password”. Reply 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 Reply 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. Reply
Thank you very
much. very use full to me. Reply 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 Reply
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. Reply 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 Reply 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. Reply I changed the if ($rows > 0) { and it worked Reply
session did not working.. plz help Reply 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. Reply
Nice information thank you Reply Glad to have a reader like you ! Your words matters a lot for us. Thanks & Regards, FormGet Team. Reply
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. Reply 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. Reply 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 Reply
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 Reply 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 Reply The required changes has been done ! Thank you so much for intimating us about this. Regards, FormGet Team. Reply
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. Reply 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. Reply
Thanks for this code.Its great help for me .I was searching for code help like this….Once again thanks.. Reply Reply
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 Reply 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. Reply
thanks for your good knowledge Reply Reply
thanks sir your hellp me in website Reply Hello Vikram, Pleased with your response. Keep following our latest posts for coding tricks and knowledge.’ Regards,
FormGet Team. Reply
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. Reply 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. Reply
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) Reply 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. Reply 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
Reply
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 Reply Hi… Thank you for this great tutorial.. Can you please post the tutorial of uploading image and save it in a
local folder? Reply 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. Reply
Good Tutorial dear. Keep it up. How to extend this example to destroy the session after some specific interval of time ? thanks. Reply 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. Reply
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 Reply 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. Reply I will be
glad if u help. Reply
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. Reply 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. Reply This is my little changed login , because of db fields>>> Can u see something wrong Reply Reply 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 Reply
How to turn off usrname and password autocomplete? Reply You article is the
bomb…I wish i could pay for every second i spent reading this Reply very good and easy undestanding login code thank you no
my web site but required domain name foe website thanks good by Reply this is very nice Reply it shows the warning as mysql_real_escape_string access denied using password no how to resolve this error Reply after logging it is not displaying profile page. what could be the reason? regards nitesh Reply
i have know php Reply i want to make logstic registration form plz send me code kindly Reply 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 Reply very informative..thanks Reply 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. Reply 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 Reply I’m having the same issue and cannot figure it out Reply 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. Reply
This paragraph will help the internet users for creating new weblog or even a weblog from start to end. Reply so useful……i dont know about thae php.now i learn little bit. Reply thanks a lot.. it helps me a lot.. Reply Isnt there supposed to be an on click code? For the login button? Reply session. php file must be included in evry page of my site to remain log in the site? Reply 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 Reply 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. Reply
It is very nice, clear code and saving my time. it works well. Thank you. Thank you… Reply 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. Reply thank you Reply 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 Reply 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 Reply 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. Reply I have created the login form but when submit, it just gives me a page of the above php code. Reply 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. Reply I enter username & password but not redirecting of profile page.. what to do???????? Reply I’m having the same problem. Any idea how to fix it? Reply
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 Reply Merry
Christmas and a hapy new year. Reply
Thankyou..:) Reply 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. Reply Reply 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? Reply 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. Reply $sql = “SELECT cad_eventos.*, login.usuario FROM cad_eventos INNER JOIN login ON cad_eventos.usuario = login.usuario”;
Reply 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 Reply 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 Reply excellent tutorial man! thank you so much Reply thier some error. i cant access the index.php Reply thanks for this. Reply 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. Reply 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 Reply
thanks Reply hi sir can you please tell me php how to create login and signup use to MYSQL Reply 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? Reply I think you should set up permissions for various user groups in your database Reply
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. Reply 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 Reply Hello. Where do I configure the database login username, password, host etc? I have webhost, so localhost won’t work. Thanks for answers 🙂 Reply thanks its working..and i have done it through your helping. Reply great help by you to me , it means alot to me. thanks again. keep posted. Reply thanks you make my project more easier. fekadu(africa,Ethiopia)! Reply 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 Reply 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? Reply 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 Reply 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 ? Reply 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 Reply 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'” Reply Realized my mistake 🙂 Reply
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. Reply Could someone please explain the need for the session.php file? Reply For storing Session Variables, making sure the user is logged in. etc. Reply
Thanks a lot dude….. it really helped me. thank you..!!!! Reply 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
Reply thanks. 🙂 Reply thank you.very well work done at here.it’s simple to understand. Reply Thank you very much very helpfullll 🙂 Reply 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 Reply I just wanted to say a big big thank you for your code,
it has helped me greatly. Thanks for sharing! Kind regards Gaza Reply Reply 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 Reply maybe you didnt start the xampp or the localhost Reply
it doesn’t work.. Reply //This webpage has a redirect loop// —whats the meaning of this? Reply Make sure you have the right information in the session.php file Reply
this code has been very helpfull. Can I get the full download Reply 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. Reply any different website is there like w3shcools Reply 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 Reply 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 Reply Reply
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. Reply ?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 Reply This is very good example Reply very helpful example of php session thank you… Reply hot do i link this together? Reply nice!!!!!! Reply I am very happy of that demo because for learn php very our help it Reply thanks Reply how to create customer profile with login session??? the login session i use your login ……… plzzz i needed ….. plzzz reply my
question…… Reply Your tutorial is very helpfull..learnt alot from it Reply 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”; } Reply Reply
very very useful codes it gives accurate results.. Reply nice post !!!!!!!!!!!!!!!!!!!! Reply Hi……… What is the use of session? And difference between session and normal login code? Reply 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! Reply 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. Reply Thanks a lot for sharing your code. Regards Neeraj FormGet Team Reply
-
Thanks a lot you made my day .. 😀 Reply Nice blog very helpful It made Login/Logout form easy to
deal with sessions in PHP Reply 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 Reply 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. Reply Would you
like to submit a tutorial based mysqli for the users ? Reply
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.! Reply Thank you so much Reply Very helpful lesson for new php learner. Reply all things are well come. Reply 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? Reply I am working in php , and your publishing is very userful to me and its too clearly i like this thank you Reply 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 Reply if(!isset($_SESSION[‘login_user’])) { header(“Location: index.php”); exit; } Reply
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. Reply Hi, I’m wondering how do I retrieve & display data from database using this session? Thanks. Reply 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? Reply Simply awesome. Reply 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 Reply Awesome description about creating
session and using session variables in PHP. Simple and Easy to Understand. Reply 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 Reply
Thank you very much Danke schönnnnnnnnnnnnnnn. German Faliminderit shummmmmmmmm. Albanian Reply sir, please send full project in php?ect name i project name is Hotel management System Reply Very very very
gooooodddd website….This is very helpful for me… Reply Very Nice system, it’s good code and security – it’s great
system. good luck man, you are a good man 🙂 Reply Hi i saw your coding it can be work login or logout ……Thank u so much…… Reply I get error at index.php line 4. It says “Parse error: syntax error, unexpected ‘if'”. How to fix it? Thanks Reply Awesome. Very Simple and straight forward. Keep it up this work. Thanks. Reply good script, thanks Reply Anyone knows why i get autofilled username and password with root.. i have disabled autofill in my browser Reply Reply
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. Reply Hello mates, its great piece of writing concerning teachingand entirely defined, keep it up all the
time. Reply Hey admin it works fine, good job. But how do i store other variables like email, rank, and so on? Reply 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 @[email protected]@CHARACTER_SET_CLIENT
*/; /*!40101 SET @[email protected]@CHARACTER_SET_RESULTS */; /*!40101 SET @[email protected]@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
[email protected]_CHARACTER_SET_CLIENT */; /*!40101 SET [email protected]_CHARACTER_SET_RESULTS */; /*!40101 SET
[email protected]_COLLATION_CONNECTION */; Reply
$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’); } Reply
thanks, your program is very good! Reply 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 🙂 Reply
Hi , This tuturial is very nice , just i show and currently i am studying
your tutorial. Reply 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? Reply 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. Reply 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 Reply 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 🙂 Reply What does your whole session.php code look like the whole file content ? Reply
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 Reply 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 Reply
Can you help me. How to make login page when the user have different database. i have admin table and i have owner table. Reply
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) Reply Hey Neeraj, Thanks a ton for the pseudo code. This saved my time. Reply 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 Reply Thank you very macho. It’s nice work Reply
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 ! Reply 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. Reply 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. Reply
how could i put these codes in www director of wamp server p/s help me am new for web development.. Reply 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. Reply
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 Reply Help? Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in public_html/Home/login.php on line 24 Reply
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. Reply Uff…! Thank You sir for sharing this. Reply thanks. works great. 🙂 😀 Reply 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. Reply
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. Reply 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. Reply
very awesome code Reply Hey, great page and worked first time and was very easy to understand. I am guessing that if I include the code Reply 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? Reply Its a good and clean code thanks very much Reply 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 Reply 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 Reply Very Nice 🙂 Reply plz help.. how can i get the SQL.file Reply 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 Reply thank you very much Reply 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”? Reply 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 ! 🙂 Reply Thanks, New knowledge for me Reply Frnz how can we link website code in cpanel to domain name. Reply why you have used the following code at the very starting of index.php ?? Reply 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 Reply thank you so much Reply 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 Reply 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 Reply 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… Reply Thanks a lot…… 🙂 i want this code…………. Reply 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. Reply 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 Reply 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 :). Reply 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 Reply 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. Reply
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 Reply 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. Reply 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 Reply
i m having trouble with connecting html website with ,my spl please tell me any ways so that i can connect them Reply In this way the session connection it’s very simple! Grazie tante from Italy Reply 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 Reply Thanks for your loginpage Reply It’s real helpful to me Reply 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. Reply Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in /Applications/XAMPP/xamppfiles/htdocs/ezbz_4/login.php on line 22
Reply This post is awesome. Really very helpful. (y) Reply 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? Reply thank you it is very informative 🙂 keep up Reply Works great, thank you to share! Also, the css file produces a clean, nice, and easy interface. Reply 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" Reply Am planning to prepare one project and need some help and suggestions. Reply 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. Reply thank you guys it help a lot . Reply 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 😛 Reply 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. Reply 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 Reply 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.. Reply Hi? I don’t think it might helped me out but frankly it gives me an idea. Thanks. Reply 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. Reply On loading index.php, browser displays that ” This web page has a redirect
loop “, so how to overcome this problem ? Reply love you nice code thank you so much but need some changes to mysqli Reply Quality articles is the crucial to be a focus for the users to visit the site, that’s what this web site is providing. Reply 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! Reply Thank you so much.. I wasted days
to find how to create a login form. This worked. (y) Keep up the good work! Reply Yes it works Reply helpful than i read b4…..thanks! Reply Nice program and self explanatory…All the best Reply This post will assist the internet people for building up new blog or even a weblog from start to end. Reply Very nice code.it usefull for mi . i like the way its describe. Reply 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. Reply Good blog post. I definitely appreciate this website. Keep writing! Reply 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. Reply How can i start a new SESSION… Eg: on my table have “Access Level”, how can i call that as a SESSION..? Reply Sir sql is not working showing error Reply Thanks for sharinjg your thoughts on php login form. Regards
Reply Making Same Please Help Me To Cpnfigure CSS And PHP Script On WAMP Reply Thanks a lot for this example, was of great use! Reply i need pdo login and registration form using php. Reply hey i just got this error Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given Reply I am genuiinely grateful to the holder of this website who has hared this wonderful paragraph at at this place. Reply 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 Reply 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 Reply It will make me happy to see
more of your codes, maybe we can create codes together as example Greetings Alex Reply
the code is really
perfect. You made my day Reply 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. Reply Excelente aporte, me sirvió. ¡Muchas
gracias! Reply Thank you for all the help you guys. i had struggled for a login page for 2years until tiday Reply You guys are awesome, help me a lot in making those Login forms. Keep It Up. Be Happy God Bless You Reply 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. Reply Thank you very much it works perfectly Reply Thank You so much. This made my day. great job. Wish The best for u you. Reply 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! Reply Thank you for this little tutorial I have Learned so Much in using session and stripslashes. Reply 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 Reply 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 Reply I have been checking out a few of your posts and i can claim nice stuff. I will make sure to bookmark your site. Reply What a fantastic page. Thank you for your help 🙂 Reply hello thank you so much for this code!!! really big help!! Reply 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 🙂 Reply Thank you sir! This is really helpfull for me to realise what the session really is. Have a nice one! Reply Thanx a lot it help the young designers like us.. Reply Work excellent Reply Perfect. Excellent tutorial. I thank you. There are many examples in NET, but yours was the only one that worked.
Congratulations Reply 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 Reply 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. Reply 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. Reply 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 Reply I love the efforts you have
put in this, thank you for all the great articles. Reply Quality content is the main to attract the viewers
to visit the web page, that’s what this site is providing. Reply This article offers clear idea for the new users of blogging, that
actually how to do blogging and site-building. Reply 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 Reply
Leave a Reply
How do I create a login session?
Table of Contents. Step 1- Create a HTML PHP Login Form.. Step 2: Create a CSS Code for Website Design.. Step 3: Create a Database Table Using MySQL.. Step 4: Open a Connection to a MySQL Database.. Step 5 - Create a Logout Session..
How do I start a PHP session?
Start a PHP Session
A session is started with the session_start() function. Session variables are set with the PHP global variable: $_SESSION.
How do I retrieve data from the database of a particular user after logging in PHP?
Retrieve or Fetch Data From Database in PHP. SELECT column_name(s) FROM table_name.. $query = mysql_query("select * from tablename", $connection);. $connection = mysql_connect("localhost", "root", "");. $db = mysql_select_db("company", $connection);. $query = mysql_query("select * from employee", $connection);.
|