Toast Message in PHP Login Form using CSS Animation

In this topic, we will learn how to display a toast alert or toast notification after a form is submitted in PHP. We will develop a simple PHP login form and display a toast message after a successful login. The toast message appears on the screen for a few seconds and disappears. It can appear from left, right, top, or bottom of the screen based on the position you define in the stylesheet.

Along with the login form, we will create a simple home page where the Login link will be displayed. If login is successful, a toast message saying "Login Successful" will appear on the home page.

You can also read the below topics:

  1. Registration and Login forms in PHP and MySQL with Session
  2. Display User Name on Header After Login Using PHP Session

How Toast Message is displayed in this application

  1. login.php - if login is successful, set a session variable to store the successful login message, like $_SESSION['toast_msg'] = 'Login Successful' and redirect to the home page
  2. index.php - In the home page, keep a position fixed to display the message and keep it hidden using styles. If $_SESSION['toast_msg'] is set, display the toast message in that position.
  3. Using the JavaScript settimeout() function show the message for 5 seconds, for example, and then make it hidden.
  4. Use CSS keyframes to animate the message, i.e., let it fade in and fade out and appear from the right side of the screen, for example, and then disappear.

Watch YouTube Video

Use Toastr Alerts in PHPFolders and Files

How to display toast message in php

We will use a folder called 'toast' under 'xampp/htdocs'.

Folder 'cfg' - Keep dbconnect.php in this folder.
Folder 'css' - Keep the custom stylesheet in this folder.

We have a simple home page (index.php), login page (login.php) and logout code (logout.php). We also have header.php. Below are the screenshots of the home and login pages:

Home Page (index.php)

display toast message in php javascript

Login Page (login.php)

show toast message in jquery

If login is successful, a toast message will be displayed as below, a message will appear from right side of the screen and fade away after 5 seconds.

display toatr message in modal popup php

Create a MySQL table

Create a table named 'users' in MySQL database. This table will have user details. The table structure is given below:

Implement Flash Messages In PHP
  1. id - primary key and auto incremented
  2. email - email id of the user
  3. name - name of the user
  4. password - password for the user
  5. signup_date - date of signup, default is current date, for information purpose only

users.sql


CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `email` varchar(255) NOT NULL,
  `name` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  `signup_date` datetime NOT NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `users` (`id`, `email`, `name`, `password`) VALUES
(1, 'test@test.com', 'Test User', '202cb962ac59075b964b07152d234b70');

ALTER TABLE `users`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `users`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;

Connect to MySQL database (dbconnect.php)

We are using the "cfg" folder to keep our dbconnect.php to connect to MySQL database.

dbconnect.php


<?php
  $server="localhost";
  $userid="root";
  $pwd="";
  $dbname="demo";
  $conn = mysqli_connect($server, $userid, $pwd, $dbname);
//Check connection
if (!$conn) 
  	die("Connection Error: " . mysqli_connect_error());

we are using the method mysqli_connect() with four parameters.

  1. server - localhost
  2. userid - root user
  3. password - no password for user root
  4. database name - demo database for this example.

You can also read the topic How to connect to MySQL database in PHP using MySQLi and PDO.

Develop a Login form (login.php)

We have developed a simple PHP login form to login using an email id and password. If login is successful, we will set a few session variables using PHP session and redirect the user to the home page.

Let us look at the code for login.php below:

login.php


<?php
include 'header.php';
 // Initilize varibles
$email = $err_msg = "";  

if (isset($_POST['submit'])) {    // if Form is submitted
	$email = trim($_POST['email']);
	$password = trim($_POST['password']);
	$password = md5($password);
	
	// check if same emailid and password are stored in the database
	$sql = "select * from users where email = '$email' and password = '$password'";
	$result = mysqli_query($conn,$sql);
	if (mysqli_num_rows($result) > 0) {
		$row = mysqli_fetch_array($result);
		$_SESSION['name'] = $row['name'];
		$_SESSION['email'] = $email;
		$_SESSION['toast_msg'] = "Login Successful";  // for displaying Toast message
		header("location:index.php");
	}
	else 
		$err_msg = "Incorrect Email id/Password";
}
	?>	
	 <form class="form-1" action="login.php" method ="post">
	 	<h2>Login Form</h2>
        <?php if ($err_msg !="") ?>
	 	<p class="err-msg"><?php echo $err_msg; $err_msg ="";?></p>
	 	<div class="form-group col-md-12">
	 		<label>Email Id</label>
	 		<input type = "text" class="form-control" name="email" id = "email" value="<?php echo $email;?>" placeholder ="Enter your Email Id" required autofocus>
	 	</div>
	 	<div class="form-group col-md-12">
	 		<label>Password</label>
	 		<input type = "password" class="form-control" name="password" id = "password" placeholder ="Enter Password" required>
	 	</div>
	 	<div class="form-group col-md-12 text-center">
	 		<a href="index.php" class="btn btn-danger">Cancel</a>  
	 		<input type="submit" class="btn btn-primary" name="submit" value="Login">
	 	</div>
	 </form>

</body>
</html>

Note in line 18, we have set a session variable for the toast message for successful login. Then, the user is redirected to the home page.

Create Home Page (index.php)

The Home page is simple. There is a heading that indicates it is the Home page and a login link if not already logged in. If the user is logged in, it displays the user name, email id and a Logout link. If toast_msg session variable is set, it will display the message.

Let us look at the code for index.php

index.php


<?php 
include 'header.php';
?>
<h1> You are at Home Page </h1>
<?php if (isset($_SESSION['toast_msg'])) { ?>
	<div id="show_msg"><?php echo $_SESSION['toast_msg'];?></div>
<?php } ?>

<?php if (isset($_SESSION['name'])) { 
echo "<h2>Welcome ".$_SESSION['name'].". Your email id is ".$_SESSION['email']."</h2>"; 
?>
<h3><a href="logout.php">Logout </a></h3>
<?php } 
else {
	?>
	<h3>Click <a href="login.php">here</a> to login</h3>
<?php } ?>

We have defined a div where we want to display the toast message. If toast_msg session variable is set, display it in this div. There are some styles used for this div to make it hidden.


#show_msg {
  min-width: 100px;
  visibility: hidden;
  background-color: #10163a;
  color: #fff;
  text-align: center;
  padding: 16px;
  position: fixed;
  border-radius: 2px;
  z-index: 1;
  top: 30%;
  right: 30px;
  font-size: 17px;
}

Even if toast_msg is set, it will not be visible. It will be visible from the JavaScripts given below. The rest of the code in index.php is self-explanatory, it just displays the name, email id and logout link if the user is logged in. Otherwise, it only shows the login link.

Add JavaScripts

We need to add JavaScript/jQuery scripts to display the message (from hidden to show) and to display it for 5 seconds, after 5 seconds it will disappear. See the below scripts:


<script>
  $(document).ready(function() {
      <?php if (isset($_SESSION['toast_msg']) && $_SESSION['toast_msg'] != '') { ?>
          var toast_msg = document.getElementById("show_msg");
          toast_msg.className = "display";
          setTimeout(function(){ toast_msg.className = toast_msg.className.replace("display", ""); }, 5000);
        <?php } 
        unset($_SESSION['toast_msg']); ?>
        });
</script>

It checks if the toast_msg session variable is set, then adds a class "display" to the div where we want to display the message. The class "display" has the properties in style.css as below:


#show_msg.display {
  visibility: visible;
  -webkit-animation: fadein 1s, fadeout 1s 4s;
  animation: fadein 1s, fadeout 1s 4s;
}

Here, the toast message is made visible with CSS animation. Fadein and fadeout for 1 second and delay fadeout by 4 seconds. Using setTimeout() function, the "display" class is removed after 5 seconds, so, the message will disappear after 5 seconds. Above JavaScript is written in index.php. Using keyframes in CSS we are adding CSS animation, see the CSS section below.

Below is the code for header.php and logout.php

header.php


<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0">
    <meta name="description" content="">
    <title>Show Toast Message</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
      <link  rel="stylesheet" href="css/style.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
    <?php
include "cfg/dbconnect.php";
if(!session_id()){
    session_start();
}
?>

logout.php


<?php
if(!session_id()){
    session_start();
}
session_unset();
session_destroy();
header("location:index.php");

Add Styles (style.css)

Below is the style.css which is included in header.php.

style.css


* {box-sizing: border-box;
}
h1,h2,h3{
  text-align: center;
}
h2{
  color:#1c47a9;
}

.err-msg{
  text-align: center;
  color:red;
}

.form-1 {
  margin: 50px auto;
  padding-bottom: 15px;
  border: 1px solid #c3c4d1;
  border-radius: 7px;
  background: #fff;
  width: 37%;
}
p{
  text-align: center;
}

#show_msg {
  min-width: 100px;
  visibility: hidden;
  background-color: #10163a;
  color: #fff;
  text-align: center;
  padding: 16px;
  position: fixed;
  border-radius: 2px;
  z-index: 1;
  top: 30%;
  right: 30px;
  font-size: 17px;
}

#show_msg.display {
  visibility: visible;
  -webkit-animation: fadein 1s, fadeout 1s 4s;
  animation: fadein 1s, fadeout 1s 4s;
}

@-webkit-keyframes fadein {
  from {right: 0; opacity: 0;} 
  to {right: 30px; opacity: 1;}
}

@keyframes  fadein {
  from {right: 0; opacity: 0;}
  to {right: 30px; opacity: 1;}
}

@-webkit-keyframes fadeout {
  from {right: 30px; opacity: 1;} 
  to {right: 0; opacity: 0;}
}

@keyframes  fadeout {
  from {right: 30px; opacity: 1;}
  to {right: 0; opacity: 0;}
}

PHP Flash MessageTest the Application

Run localhost/toast in the browser. You will see the home page displayed. See the below screen:

PHP Flash Message with toastr

Click on Login from the home page. enter email id as test@test.com, password as 123. You should be able to see a toast message of successful login appear from the right end of the screen and disappear after a few seconds. Also, you should see the user name, email id and Logout link displayed on the home page.

Login form for toast message in PHP

Toast alert in PHPNote

Here, we have redirected the user to the home page, so we have written code for the toast message in index.php including JavaScript. If you redirect the user to a different page after successful login, then you need to write the code for displaying the toast message in that page.

download source code to display Toast message in PHPDownload Source Code

Click on the Download button to download the source code.

display toast message in php javascriptConclusion

Displaying a toast alert is a popular way to show messages to the users. You can display it after a user action is performed. In your project, you can try adding a toast message wherever possible. I hope this topic will help you.

Post a Comment

Save my Name and Email id for future comments