Login And Logout Using Session In PHP And MySQLi (2024)

Last Updated : Mar 11, 2024

IN - PHP MySQLi | Written & Updated By - Ashish

Login And Logout Using Session In PHP And MySQLi (1)

In this tutorial we will show you the solution of login and logout using session in PHP and MySQLi, here we created login form with two input fields for collecting user name, password and when user clicks submit button we validating and verifying whether user is information validate or not.

If those are valid then only we storing user information on session variable and redirected another page there we displaying user name by using session variable and logout option.

When we storing some information’s on session we can access those from any different page in website.

Step By Step Guide On Login And Logout Using Session In PHP And MySQLi :-

Here we defined login form with input fields for collecting user name, password and another one is submit button then when clicks submit button we validating each input fields using empty() method if both fields are empty it throws error.

Otherwise we executes database connection using select query we collecting which row in table data matched with user details and stored to variable $query.

We checking whether row count is not equal to zero or not if it is true we storing collected row name,password on respective variables ‘$dbusername,$password’ then we checking both user and database details are same.

If both are same then only we starting session and storing user name on session variable.

Lastly we navigate to member page otherwise it throws error message.

In member page we displaying user name by using session variable with logout option and without login when user tries to open member’s page we redirecting them to login page.

When user clicks on logout link its loads logout external file there we destroying session and we unsets session variable to none.

<!doctype html><html><head><title>Login</title></head><body><center><h1>LOGIN FORM</h1></center><form action="" method="POST">Username: <input type="text" name="user"><br />Password: <input type="password" name="pass"><br /><input type="submit" value="Login" name="submit" /></form><?phpif(isset($_POST["submit"])){if(!empty($_POST['user']) && !empty($_POST['pass'])) { $user=$_POST['user']; $pass=$_POST['pass']; $con=mysqli_connect('localhost','root','','dbase') or die(mysql_error()); $query=mysqli_query($con,"SELECT * FROM info WHERE Name='".$user."' AND Password='".$pass."'"); $numrows=mysqli_num_rows($query); if($numrows!=0) { while($row=mysqli_fetch_assoc($query)) { $dbusername=$row['Name']; $dbpassword=$row['Password']; } if($user == $dbusername && $pass == $dbpassword) { session_start(); $_SESSION['sess_user']=$user; header("Location: member.php"); } } else { echo "Invalid username or password!"; }} else { echo "All fields are required!";}}?></body></html>

member.php

<?phpsession_start();if(!isset($_SESSION["sess_user"])){ header("location:login.php");} else {?><!doctype html><html><head><title>Welcome</title></head><body><h2>Welcome, <?=$_SESSION['sess_user'];?>! <a href="logout.php">Logout</a></h2></body></html><?php}?>

logout.php

<?phpsession_start();unset($_SESSION['sess_user']);session_destroy();header("location:login.php");?>
  1. A php script can be placed anywhere in the document. A php script starts with <?php and end with ?>.
  2. The default file extension for php files is “.php” and php statements end with ‘;’ semicolon.
  3. In html block we defined login form with input fields username, password and submit button and when user filling details and clicks submit using if condition we checks whether submit is set or not by isset() method.
  4. If returns true we checks another condition for validating both input fields are filled or not by user if both are not empty then we executed database connection by mysqli_connect() method.
  5. The mysqli_connect() method will executes database connection for that we need to pass four parameters ‘host name, user name, password, database name’ properly then only we can successfully make connection otherwise it throws error.
  6. Using select query we collecting data from table ‘info’ by condition which row had username, password match with user entered username, password then it is stored to variable $query.
  7. Then we checking whether $query count is more than value ‘0’ if is true then using while loop we fetching table data and stored to respective variables ‘$dbusername,$dbpassword’.
  8. Using another if condition we checks both database and user entered details are same then we starts session and stored current username on session variable so we can access that session value any page in website and redirected to member.php page by header() method.
  9. Otherwise it will throw’s error on webpage. In member.php file we are checking whether any user without login they navigate to this link and access anything we redirecting them to login page. Otherwise welcome message displayed with current user name and logout option because we cant leave our account page as it can anyone access so we provided logout link.
  10. When user clicks logout it loads logout script file, here we destroyed session and also we unsets session variables so it had no more detail about of users.

Conclusion :-

In conclusion we are able to know how to create login form with session and validation using php.

First we need to start our xampp server then we load this program on browser we can see result of login page when user filled input fields and clicks login then we validating whether all input fields filled by user and if condition checks entered user information with database if they correct then we are navigate to member page there using session variable we displayed current user name with welcome message.

I hope this tutorial on login and logout using session in PHP and MySQLi helps you and the steps and method mentioned above are easy to follow and implement.

Login And Logout Using Session In PHP And MySQLi (2) About Ashish

Ashish is a dynamic and motivated individual with a passion of programming and an experienced programmer having 3+ years of experience in various languages like Java, Python, HTML, CSS, JavaScript, jQuery and various frameworks like Bootstrap

Follow Ashish On Linkedin 🡪

POPULAR TUTORIALS

  • How To Fetch Data From Database In JavaScript Using Ajax
  • HTML Background Image No-Repeat Without CSS
  • CSS Opacity Background Image
  • Admin And User Login In PHP And MySQL Database
  • CSS Hover Transition Effects
  • Create JSON File Python
  • CSS Hover Effects Image
  • CSS Animations On Hover
  • HTML Background Image Full Screen Without CSS
  • Passing JavaScript Variable To PHP In The Same Page
Login And Logout Using Session In PHP And MySQLi (2024)
Top Articles
Wright-Patt Credit Union on LinkedIn: Since April 1, 2024, we’ve had 302 member winners awarded $11,825 in…
Paloma Valley's robotics Team Axolotl wins national title
Devotion Showtimes Near Xscape Theatres Blankenbaker 16
Katie Nickolaou Leaving
Katmoie
Southside Grill Schuylkill Haven Pa
Triumph Speed Twin 2025 e Speed Twin RS, nelle concessionarie da gennaio 2025 - News - Moto.it
Myhr North Memorial
Songkick Detroit
7543460065
Mylife Cvs Login
Swimgs Yung Wong Travels Sophie Koch Hits 3 Tabs Winnie The Pooh Halloween Bob The Builder Christmas Springs Cow Dog Pig Hollywood Studios Beach House Flying Fun Hot Air Balloons, Riding Lessons And Bikes Pack Both Up Away The Alpha Baa Baa Twinkle
Rainfall Map Oklahoma
Max 80 Orl
What’s the Difference Between Cash Flow and Profit?
Raid Guides - Hardstuck
Overton Funeral Home Waterloo Iowa
Available Training - Acadis® Portal
Daily Voice Tarrytown
使用 RHEL 8 时的注意事项 | Red Hat Product Documentation
Faurot Field Virtual Seating Chart
Veracross Login Bishop Lynch
Riherds Ky Scoreboard
Busted Mcpherson Newspaper
Www.patientnotebook/Atic
Hannaford Weekly Flyer Manchester Nh
Craig Woolard Net Worth
Kirk Franklin Mother Debra Jones Age
The Eight of Cups Tarot Card Meaning - The Ultimate Guide
Tinyzonehd
This Is How We Roll (Remix) - Florida Georgia Line, Jason Derulo, Luke Bryan - NhacCuaTui
Planned re-opening of Interchange welcomed - but questions still remain
Grand Teton Pellet Stove Control Board
Nicole Wallace Mother Of Pearl Necklace
Walter King Tut Johnson Sentenced
Cars And Trucks Facebook
Justin Mckenzie Phillip Bryant
Barrage Enhancement Lost Ark
Arcadia Lesson Plan | Day 4: Crossword Puzzle | GradeSaver
Merge Dragons Totem Grid
SF bay area cars & trucks "chevrolet 50" - craigslist
Vivek Flowers Chantilly
A Comprehensive 360 Training Review (2021) — How Good Is It?
60 X 60 Christmas Tablecloths
Live Delta Flight Status - FlightAware
Mugshots Journal Star
'The Nun II' Ending Explained: Does the Immortal Valak Die This Time?
How the Color Pink Influences Mood and Emotions: A Psychological Perspective
18 Seriously Good Camping Meals (healthy, easy, minimal prep! )
Minute Clinic Mooresville Nc
Room For Easels And Canvas Crossword Clue
Primary Care in Nashville & Southern KY | Tristar Medical Group
Latest Posts
Article information

Author: Catherine Tremblay

Last Updated:

Views: 6439

Rating: 4.7 / 5 (47 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Catherine Tremblay

Birthday: 1999-09-23

Address: Suite 461 73643 Sherril Loaf, Dickinsonland, AZ 47941-2379

Phone: +2678139151039

Job: International Administration Supervisor

Hobby: Dowsing, Snowboarding, Rowing, Beekeeping, Calligraphy, Shooting, Air sports

Introduction: My name is Catherine Tremblay, I am a precious, perfect, tasty, enthusiastic, inexpensive, vast, kind person who loves writing and wants to share my knowledge and understanding with you.