3 ways to redirect back to same page after login – PHP
In this article, we will learn how to redirect the user back to the same page after he has successfully logged-in. We will be using PHP in this tutorial.
3 ways to redirect back to same page after login – PHP
You may have seen a lot of websites where you can see it’s content. But in order to perform some action you have to login first. When you click on login you are redirected to some other page where you can enter your email and password and login. After a successfull login, they redirect you back to the same page where you clicked “Login” button. Another way is that they show you a pop-up on the same page, after login you can perform that action.
That is a very useful functionality. Specially if you want user to see the content of website without having to login.
For example, in Facebook you can see videos, pictures and profiles. But in order to like/comment/share or send message/friend request you have to login. So we are going to discuss 3 methods to do that, we will be using a sample database named classicmodels it will be included in the source files below:
Method 1 – URL
This is the same technique as we have discuss in the 1st paragraph of this post. We are going to create 3 pages, home.php, Http.php and method-1-url.php. Home.php will be the page where we will be creating a “Login” button and method-1-url.php will be the page that will show the login page. The Http.php is the page responsible for handling form submission and database queries.
home.php
Here we are appending the complete path of current page in the URL:
<?php
// Required for $_SESSION variable
session_start();
// Check if user is logged in
if (isset($_SESSION["user_id"]))
echo "<p>You are logged in</p>";
// Complete path to this page
$actual_link = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
?>
<a class="btn btn-primary" href="method-1-url.php?continue=<?php echo $actual_link; ?>">Login</a>
method-1-url.php
Here we are appending the continue variable in the form action attribute received from home.php file:
<form method="POST" action="Http.php?continue=<?php echo $_GET['continue']; ?>">
<input name="username">
<input name="password" type="password">
<input name="method_1_login" type="submit">
</form>
Http.php
This file is responsible for all your login logic:
<?php
// Required to use $_SESSION for login
session_start();
// Connecting with database
$connection = mysqli_connect("localhost", "root", "", "classicmodels");
// Check if form is submitted
if (isset($_POST["method_1_login"]))
{
// Checking credentials
$sql = "SELECT * FROM users WHERE email = '" . $_POST["username"] . "' AND password = '" . $_POST["password"] . "'";
$result = mysqli_query($connection, $sql);
if (mysqli_num_rows($result) > 0)
{
// Save user ID in $_SESSION variable
$_SESSION["user_id"] = mysqli_fetch_object($result)->id;
// Redirecting back to same page where "Login" button was clicked
header("Location: " . $_GET["continue"]);
}
else
echo "Incorrect password";
}
Method 2 – PHP
This method involves using the built-in PHP $_SERVER variable to do the task. The login form is faily simple and there is no additional parameter in the URL:
<?php
session_start();
if (isset($_SESSION["user_id"]))
echo "<p>You are logged in</p>";
?>
<form method="POST" action="Http.php">
<input name="username">
<input name="password" type="password">
<input name="method_2_login" type="submit">
</form>
Http.php
Here all the login logic will remain same as in previous step, only needs to change the way we redirect back:
..........
header("Location: " . $_SERVER["HTTP_REFERER"]);
..........
Method 3 – AJAX
This method involves using an AJAX request to do the task. The login form is faily simple and there is no additional parameter in the URL, instead of having action attribute we are using onsubmit event to prevent the form from submitting and sending the data using AJAX:
<?php
session_start();
if (isset($_SESSION["user_id"]))
echo "<p>You are logged in</p>";
?>
<form method="POST" onsubmit="return doLogin(this);">
<input name="username">
<input name="password" type="password">
<input name="method_3_login" type="submit">
</form>
<script>
function doLogin(form) {
/* Create an AJAX object */
var ajax = new XMLHttpRequest();
/* 1st param is method, 2nd is name of file, 3rd is asynchronous */
ajax.open("POST", "Http.php", true);
/* Content type is required for POST requests */
ajax.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
/* Called each time status of request changes */
ajax.onreadystatechange = function () {
/* Ensures response is successfully received from server */
if (this.readyState == 4 && this.status == 200)
window.location.reload();
};
/* Actually sending the request with all form data */
ajax.send("username=" + form.username.value + "&password=" + form.password.value + "&method_3_ajax=1");
/* Prevent form from submitting */
return false;
}
</script>
Http.php
Here all the login logic will remain same as in previous step, only needs to change the way we redirect back. As it is an AJAX request we will not be doing the HTTP redirect but will just be sending the response back to AJAX. The response can be any string you want but for the sake of simplicity we are just sending “Successfully logged in” string:
..........
echo "Successfully logged in";
// Required to stop the script from further executing
exit();
..........
Learn more
2 factor Login Authentication – PHP & Twilio SMS
[wpdm_package id=’148′]
Great post. I was checking constantly this blog and I’m
impressed! Very helpful information particularly the last part :
) I care for such info much. I was seeking this certain information for
a very long time. Thank you and good luck.