Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect to the last page requested after login

I need help regarding my login system. In my project when a user logs in they simply go to their account. If they are browsing some pages and asked to login then they should redirect to that page after login and not their profile page.

Here is the code I am trying for this but the user is always redirected to student_account.php and not the requested page.

$fetch = mysql_fetch_assoc($exec);
        $_SESSION['login'] = $fetch[uniq];
            $_SESSION['emailid'] = $fetch['email'];
            $emailid = $_SESSION['emailid'];

        $_SESSION['type'] = 'student';
        if(isset($_SESSION['url'])) 
   $url = $_SESSION['url']; // holds url for last page visited.
else 
   $url = "student_account.php"; // default page for 

header("Location:$url"); 
like image 364
Dinesh Avatar asked Nov 29 '22 16:11

Dinesh


2 Answers

You can paste this code into all your pages on your website:

<?php
session_start(); 
$_SESSION['url'] = $_SERVER['REQUEST_URI']; 

And then for the login page you can have:

<?php
session_start();  // needed for sessions.
if(isset($_SESSION['url'])) 
   $url = $_SESSION['url']; // holds url for last page visited.
else 
   $url = "student_account.php"; 

header("Location: http://example.com/$url"); 
like image 69
Yogus Avatar answered Dec 05 '22 23:12

Yogus


I think you should try HTTP_REFERER here to redirect on last visited page. for that set a hidden field in your login form.

HTML :-

<input type="hidden" name="redirurl" value="<? echo $_SERVER['HTTP_REFERER']; ?>" />

and get redirurl value in form post.

PHP :-

if(isset($_REQUEST['redirurl'])) 
   $url = $_REQUEST['redirurl']; // holds url for last page visited.
else 
   $url = "student_account.php"; // default page for 

header("Location:$url");

Or if you are using session then please ensure that you start session session_start() on that page. otherwise session will break and it couldn't save your desired URL.

like image 36
Roopendra Avatar answered Dec 05 '22 22:12

Roopendra