Simplest way to create login and logout in PHP using PHP session

0
php login and logout using php sessoin and php cookies by jeamshiv

Hello Newbies, Today, I will tell you the simplest way to handle login and logout in PHP. I will tell you how you can create a login system in PHP without using MySQL. We will PHP session handlers function, which will help us to create a login and logout system.

How to store PHP session data?

It is the simplest way to store user data in a PHP session.

<?php 
 
 	session_start();
 	$_SESSION["name"] = "Shiv";

  ?>

The important thing if you are using PHP sessions.

If you are using a PHP session, it is necessary to put seesion_start(); at the top of the starting code. If you forget to write at the top of your code session will not work properly.

Let's create session in PHP.

First of all, we will create an index.php, and we will code a form with submit button. We will store form data in the PHP session.

<?php session_start(); ?>

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>PHP Session</title>
</head>
<body>
	
	<form action="controller.php" method="POST" role="form">
		
	
		<div class="form-group">
			<label for="">Your Name</label>
			<input type="text" name="user_name" placeholder="Type your name">
		</div>
	
		
	
		<button type="submit">Submit</button>
	</form>

</body>
</html>

In the above code, we have created a form, and the action of this form is controller.php, and in the controller.php, we will store the user name in the session. Now open the controller.php page into another tab, or in a new chrome window, it will show the user name.

Let's create our controller.php file.

<?php 
	session_start();

	if($_SERVER["REQUEST_METHOD"] == "POST"){
		
		$name = $_POST["user_name"];

		$_SESSION["user"] = $name;
		echo "User sessoin has been saved <br>";
		echo "<a href='controller.php' target='_blank'>Click HERE</a>";

	} else {

		echo "<h1>Name of the user is ". $_SESSION["user"]. "</h1>";
	}

	
 ?>

How to destroy user sessions in PHP?

And the last one, we will create a logout.php page. It will help us to destroy the user's session. It is the simplest thing to do in php session.

<?php 
	session_start();
	session_destroy();
	header("Location: login.php");
 ?>

Let's understand the difference between PHP sessions and PHP cookies.

Php session and PHP cookies both are somehow the same.

PHP Session

  1. Browser store the data.
  2. Data saved until the browser open.
  3. Web developers prefer it to use.

PHP Cookies.

  1. Your computer store the data.
  2. Data saved permanently.
  3. Web developers less prefer it to use.

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Post a Comment (0)
Our website uses cookies to enhance your experience. Learn More
Accept !