This one is for that situation where you want the user to login from a page (say pageA.php) and after the credentials have been verified, you want the session to start but the user should stay on the same page.
First of all, you'll need to start the session in your php code - which, if you are using session-based authentication, should already exist in your code.
Something like:
<?php
session_start();
Now, to this you could add something like this:
$_SESSION['url'] = $_SERVER['REQUEST_URI'];
What this does is, sets the URI in the session using the php variable $_SERVER, as the current URL. This URL is the one that we will redirect to in our login.php (or whatever you've named that file) if the authentication has been successful.
So, in all pages on your website, you'll need to start with something like:
<?php session_start();
ob_start();
$_SESSION['url'] = $_SERVER['REQUEST_URI'];
?>
Again, this could simply be included in a header file so you dont have to manually add these lines in all pages.
Once this has been done, in your login.php, simply add the following lines after the statement that checks for authentication:
if(isset($_SESSION['url']))
$url = $_SESSION['url'];
else
$url = "whatever page you want the user to be redirected to if the session wasnt able to capture the URL";
header("location: $url"); //this will redirect the user to previous URL, if set in the session
Hope this is useful in some way!
Cheers!
Great Post, Actually PHP is a beautiful source for developing a database driven web application, I love this post, thanks for spending your time for discussing about this topic.
ReplyDeleteRegards,
PHP Institutes in Chennai
thanks a lot Roshini RS!
Delete