Skip to main content

Effortless User Registration and Login with Sessions and Cookies in PHP

Simple Registration Login with Session and Cookie


We will complete this "Simple Registration/Login" in two steps:
1) Database.
2) Design and PHP code/Connecting to the Database.

But before we can start, first of all, you need to install the Web Server like Xampp / Wampp. I have a Xampp So let's get started:


1) Database:

a) Open your browser and write in the browser's address bar: 'localhost/phpmyadmin' and then enter the Admin panel of MySQL database will open.

b) Left upper corner you can see 'new' click on that and create your database by writing 'Database_name' and clicking  the 'Go' button.

c) Go to the 'SQL' tab and copy & paste the below code and click on the 'Go' button



-- phpMyAdmin SQL Dump
-- version 4.8.4
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Mar 28, 2019 at 08:23 AM
-- Server version: 10.1.37-MariaDB
-- PHP Version: 7.3.0

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
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 utf8mb4 */;

--
-- Database: `session_demo`
--

-- --------------------------------------------------------

--
-- Table structure for table `users`
--

CREATE TABLE `users` (
  `users_id` int(5) NOT NULL,
  `users_name` varchar(50) NOT NULL,
  `users_email` varchar(50) NOT NULL,
  `users_password` varchar(50) NOT NULL,
  `users_image` varchar(255) NOT NULL,
  `users_create_date` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `users`
--

INSERT INTO `users` (`users_id`, `users_name`, `users_email`, `users_password`, `users_image`, `users_create_date`) VALUES
(1, 'Admin', 'admin@gmail.com', 'admin', '5e52b90003b588d3456f77a925fc62f5.jpg', '2019-03-28 00:00:00'),
(4, 'user-2', 'user-2@gmail.com', 'user-2', 'child-678335_1920.jpg', '2019-03-28 08:21:29');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `users`
--
ALTER TABLE `users`
  ADD PRIMARY KEY (`users_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
  MODIFY `users_id` int(5) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
COMMIT;

/*!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 */;



d) Your Database is created now.


2 & 3) Design and PHP Code:

a) First of all you create 'config.php' for the database configuration code or connect the database to your project.



<?php
$con = mysqli_connect('localhost','root','','session_demo');
?>



b) Now you want to create 'index.php' for the registration of the user:


<?php
include("config.php");
?>
<!DOCTYPE html>
<html>
<head>

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<title>Register</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">

</head>
<body>
<div class="container">
                        <h2>Registration</h2>
<form method="post" action="" enctype="multipart/form-data">
<input type="text" name="name" class="form-control" placeholder="Name"/>
<input type="email" name="email" class="form-control" placeholder="Email"/>
<input type="password" name="password" minlength="5" maxlength="10" class="form-control" placeholder="Password"/>
<input type="file" name="img" class="form-control"/>
<input type="submit" class="btn btn-primary" name="submit" value="Register"/>&emsp;
<a href="login.php">Login</a>
</form>
</div>
</body>
</html>
<?php
if(isset($_POST['submit']))
{
$name = $_POST['name'];
$email = $_POST['email'];
$password = $_POST['password'];
$image = $_FILES['img']['name'];
$temp_name = $_FILES['img']['tmp_name'];
move_uploaded_file($temp_name,"img/$image");
$date = date("Y-m-d H:i:s A");

$result = mysqli_query($con,"SELECT users_email FROM users WHERE users_email='$email'");
$num = mysqli_num_rows($result);
if($num > 0)
{
echo "<script>alert('Try Unique Email.')</script>";
}
else
{
mysqli_query($con,"INSERT INTO users VALUES ('','$name','$email','$password','$image','$date')");
echo "<script>confirm('Registered.')</script>";
}
}

?>



c) Now you create 'login.php' for the login user:


<?php
session_start();
include("config.php");
?>
<!DOCTYPE html>
<html>
<head>

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<title>Login</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">

</head>
<body>
<div class="container">
                        <h2>Login</h2>
<form method="post" action="">
<input type="email" name="email" class="form-control" placeholder="Email"/>
<input type="password" name="password" minlength="5" class="form-control" placeholder="Password"/>
<input type="submit" class="btn btn-primary" name="login" value="Login"/>&emsp;
<a href="index.php">Register</a>
</form>
</div>
</body>
</html>
<?php
if(isset($_POST['login']))
{
$email = $_POST['email'];
$password = $_POST['password'];

$result = mysqli_query($con,"SELECT * FROM users WHERE users_email LIKE '$email' AND users_password LIKE '$password'");
$num = mysqli_num_rows($result);
if($num)
{
setcookie("User","Sourabh",time()+(86400*30));
$_SESSION['userData'] = mysqli_fetch_assoc($result);
header('Location: home.php');
}
else
{
echo "<script>alert('Invalid Email/Password.')</script>";

}
}

?>


d) Now you create 'home.php' which is a redirect page after login user:


<?php
session_start();
if(!isset($_SESSION['userData']))
{
header('Location: login.php');
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<title>Register</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
<style type="text/css">
img
{
width: 185px;
    height: 197px;
}
</style>
</head>
<body>
<div class="container">
Welcome <?php echo $_SESSION['userData']['users_email']; ?>.
Logout from <a href="logout.php">Home</a>
<div class="container" style="margin-top: 100px">
<div class="row justify-content-center">
<div class="col-md-2">
<img src="img/<?php echo $_SESSION['userData']['users_image']; ?>">
</div>

<div class="col-md-10">
<table class="table table-hover table-bordered">
<tbody>
<tr>
<td>ID</td>
<td><?php echo $_SESSION['userData']['users_id']; ?></td>
</tr>
<tr>
<td>Name</td>
<td><?php echo $_SESSION['userData']['users_name']; ?></td>
</tr>
<tr>
<td>Email</td>
<td><?php echo $_SESSION['userData']['users_email']; ?></td>
</tr>
<tr>
<td>Account Creation Date</td>
<td><?php echo $_SESSION['userData']['users_create_date']; ?></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>

</div>
</body>
</html>



e) Now you create 'logout.php' for users logout and redirect to the login page and also destroy their session and cookie from your browser:


<?php
session_start();
setcookie("User","Sourabh",time()-(86400*30));
unset($_SESSION['userData']);
header('Location: login.php');
?>








😃 Embrace the joy of coding!

Comments

Popular posts from this blog

Getting Started with Node.js: Setting Up Your Development Environment

Introduction:   Node.js has revolutionized the way we build server-side applications and JavaScript-based tools. Whether you're a seasoned developer or just starting your journey, setting up a solid Node.js development environment is essential for efficient and enjoyable coding. In this article, we'll guide you through the process of setting up a basic Node.js environment on your machine. Table of Contents:  Installing Node.js and npm Creating Your First Node.js Application Understanding Package.json Using npm Packages Setting Up a Simple Web Server Debugging and Testing Your Node.js Code Version Control with Git Installing Node.js and npm:   Node.js comes bundled with npm, the Node.js package manager. To install Node.js, visit the official Node.js website and download the installer for your operating system. Follow the installation wizard, and make sure to include npm during installation. You can verify the installation by running node -v and npm -v in your terminal. Cre...

Understanding Asynchronous JavaScript: Exploring async/await, Promises, and Callbacks

  Asynchronous programming is a fundamental aspect of JavaScript that allows you to execute code without blocking the main execution thread. It enables tasks like fetching data from APIs, reading files, or handling user interactions to be executed without freezing the entire application. In this article, we'll dive into the concepts of async/await, Promises, and callbacks – powerful tools that make managing asynchronous operations more elegant and efficient. Callbacks: The Traditional Approach Callbacks are the foundation of asynchronous programming in JavaScript. A callback is a function that is passed as an argument to another function. It's executed after the completion of an asynchronous operation. However, using callbacks can lead to callback hell – a situation where nested callbacks become hard to manage and read. Example: function fetchData(callback) {   setTimeout(() => {     const data = 'Hello, world!';     callback(data);   }, 1000); } fe...

Understanding JavaScript Variables: var, let, and const Explained

  In the dynamic world of JavaScript, the way you declare and use variables can greatly impact your code's behavior and performance. With the introduction of ES6 (ECMAScript 2015), JavaScript developers gained more flexibility and control over variable declarations through the use of three keywords: var, let, and const. In this blog, we'll dive into the differences between these keywords and explore when to use each one. Understanding var, let, and const: var :  The Old Way The var keyword was the traditional way to declare variables in JavaScript. However, it has some quirks that can lead to unexpected behaviors. Variables declared with var are function-scoped, meaning they are accessible within the function where they are declared or globally if declared outside of a function. This scope behavior often caused issues in complex codebases. let :  The Block-Scope Hero ES6 introduced the let keyword to address the scoping issues of var. Variables declared with let are block...