Jump to content

Redirect to target page after login


perky416

Recommended Posts

Hi guys,

 

Please could someone give me some pointers on how i would go about redirecting the user to the page they were trying to visit after being prompted to login?

 

Using phpfreaks as an example, I try to reply to a thread whilst logged out, i get taken to the login page, then after login i get taken to the page where i can enter my reply.

 

At the moment my users get redirected to their account page after login is successfull using the header function.

 

Many thanks.

Link to comment
Share on other sites

When the user is not loggged in. In each page  you'll want to set a session variable (call it targetPage) on the current page the user is on. When the user goes to login and is successful before redirecting the user check whether the session variable $_SESSION['targetPage'] exists. If it does redirect the user to the target page otherwise go to their account page.

 

You'll have something like this at the top of your pages

session_start();

// set the targetPage session for users that are not logged in
// change $_SESSION['loggedIn'] to the variable you use for identifying whether a user is logged in.
if(!isset($_SESSION['loggedIn']))
{
    // set the target page to the current page being viewed
    $_SESSION['targetPage'] = $_SERVER["REQUEST_URI"];
}

That code will need to be placed before any code you use for redirecting the user to the login page.

 

Then in your login page you'll have this code when redirecting the user

// check that the targetPage exists
if(isset($_SESSION['targetPage']) && !empty($_SESSION['targetPage']))
{
     // it exits, redirect the user to the targetPage url
     $redirectUrl = $_SESSION['targetPage'];

     // remove the the targetPage session
     $_SESSION['targetPage'] = '';
     unset($_SESSION['targetPage']);
}
else
{
    // change this to your user account page
    // we'll redirect the user to their account page if targetPage is not set.
    $redirectUrl = 'user-account-page.php';
}

// redirect the user
header('Location: http://www.yoursite.com/' . $redirectUrl);

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.