• 0

[PHP] redirect back to page after logging in


Question

Hey,

does anyone know where I can get a script that will redirect my users back to the page they were viewing after logging in?

if i have user page2.php and they aren't logged in, they will be redirected to the index.php where the login page is. after login in how can they be taken back to page2.php where the content is viewable only if you are registered and logged in...

16 answers to this question

Recommended Posts

  • 0

When they first visit the login page, look at the $_SERVER['HTTP_REFERER'] variable and either save the referring address in the session, or save a default address in the session if there was no referrer page. After they log in, redirect them to the address you stored in the session.

  • 0
  On 03/05/2010 at 02:46, Andrew Lyle said:

Since your using php, try:

header('Location : http://www.website.com/page2.php');

The problem with that is it is not really dynamic enough, he wants them to return to whatever page they were on before hitting log in, page2.php was simply an example he used. You could however use that along with the first responses solution so you are able to grab the page they came from, then redirect them back there after login using the header function. But, I am not PHP expert (I have experience in it, but far less than many others)....so there may be a better way to handle it.

  • 0

What he could do, my original thought, but wanted to provide him with what he requested, is use a cookie or session, very easy to code.

And just enable parts of the page if the login returns successful.

  • 0

I have it

if (!isset($_SESSION['user_id']))
{
header("Location: account.php");
}

which redirects the user back to account.php after login in.

but if the user was on a different page i would like them to be taken back to that same page dynamically after logging in.

Its cause after my session expires the user will be directed to the login page but then the login page directs them to the default page. I wanted them to be taken back to the page they were on after login in...

  • 0
  On 03/05/2010 at 03:27, saiya said:

I have it

if (!isset($_SESSION['user_id']))
{
header("Location: account.php");
}

which redirects the user back to account.php after login in.

but if the user was on a different page i would like them to be taken back to that same page dynamically after logging in.

Its cause after my session expires the user will be directed to the login page but then the login page directs them to the default page. I wanted them to be taken back to the page they were on after login in...

take a look at this page: http://ca.php.net/reserved.variables.server & http://www.tizag.com/phpT/phpsessions.php

My best bet would be to store each page as a session, excluding the login page. Once the user has finished the login section, read the session and add it to

header("Location: ". $_SESSION['page']);

  • 0

Simply use:

<?php
$ref = $_SERVER['HTTP_REFERER'];
header( 'refresh: 0; url='.$ref);
?>

You can change the refresh limit depending on if you choose to display a message.

(I use this myself and it works a treat, any problems don't hesitate to message me :))

  • 0
  On 03/05/2010 at 07:35, Tom Bonez said:

Simply use:

<?php
$ref = $_SERVER['HTTP_REFERER'];
header( 'refresh: 0; url='.$ref);
?>

You can change the refresh limit depending on if you choose to display a message.

(I use this myself and it works a treat, any problems don't hesitate to message me :))

Hmmmm, well after looking around the PHP.net sitr I put this together

function page_protect() {
session_start();

//check for cookies
if(isset($_COOKIE['user_id']) && isset($_COOKIE['username'])){
 	$_SESSION['user_id'] = $_COOKIE['user_id'];
 	$_SESSION['username'] = $_COOKIE['username'];
 }

if (!isset($_SESSION['user_id']))
{
$_SESSION['login_retval'] = $_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'] ; // <- This is what I updated it with, I haven't tried it yet, but I got a feelings its wrong lol
header("Location: account.php");
}

  • 0
  On 03/05/2010 at 08:00, saiya said:

Hmmmm, well after looking around the PHP.net sitr I put this together

function page_protect() {
session_start();

//check for cookies
if(isset($_COOKIE['user_id']) && isset($_COOKIE['username'])){
 	$_SESSION['user_id'] = $_COOKIE['user_id'];
 	$_SESSION['username'] = $_COOKIE['username'];
 }

if (!isset($_SESSION['user_id']))
{
$_SESSION['login_retval'] = $_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'] ; // <- This is what I updated it with, I haven't tried it yet, but I got a feelings its wrong lol
header("Location: account.php");
}

Didn't read the part about it redirecting to index.php for login, I'd personally code this differently. If you don't find a solid solution to your problem when I've had some sleep I'll drop you a line :)

  • 0
  On 03/05/2010 at 08:35, Tom Bonez said:

Didn't read the part about it redirecting to index.php for login, I'd personally code this differently. If you don't find a solid solution to your problem when I've had some sleep I'll drop you a line :)

ya, actually i'm pretty drain too. I'm going to bed now... been tinkering with this and and upload image script i'm getting headaches over.

you can check that out too if you would like to give some feed back ;)

https://www.neowin.net/forum/topic/897196-phpmysql-compare-session-info-to-db-in-a-query/page__gopid__592575702entry592575702

but yes, I think I'm not thinking about this correctly and might need some help getting the referral thing to work.

My thing was to have this scenario

index.php has login details, that when logged in takes you to account.php

say you access www.mysite.com/upload.php without being logged in, my page_protect() will take you to the index.php to login. But onces logged in instead of being redirected to account.php to be redirected to upload.php...

  • 0

I'm no expert on the subject, but the suggestions in this thread are a great way to introduce XSS and injection vulnerabilities. All I'd have to do is set a cookie with a valid userid and username and get to someone else's account page.

  • 0
  On 04/05/2010 at 08:03, boogerjones said:

I'm no expert on the subject, but the suggestions in this thread are a great way to introduce XSS and injection vulnerabilities. All I'd have to do is set a cookie with a valid userid and username and get to someone else's account page.

well the cookies are sha1 with a salt. you would need to have to guess the entire string for it to match, I have a check on my pages also that the page cannot be accessed unless

user_id matches a md5(user_id) and the password in the cookie doesn't match the sha1(password) from the database.

Its probably still not fully protected, but since I'm learning this is how i figured...

  • 0

One solution i have seen is to append the previous url to the query string, ie like

if (!isset($_SESSION['user_id']))
{
header("Location: index.php?nav=".$whateverpageyouwerebrowsingbefore
// $whateverpageyouwerebrowsingbefore would be something like /account/, /main/ or whatever

It's not much different than storing in a cookie the previous page, but it still need to be sanitized/validated against a list of permitted/allowed urls (or uri segments) you can include an associative array in all your page which maps your "route" to the correct redirect page. As for storing session information in a cookie : bad idea imo you should always store unimportant information in a cookie, even if it's encrypted, session are much more secure in this regard (even though you have to protect your app from session fixation vulnerabilities, but any serious dev will always do that unless they don't use sessions).

  • 0
  On 04/05/2010 at 08:24, kyosuken said:

One solution i have seen is to append the previous url to the query string, ie like

if (!isset($_SESSION['user_id']))
{
header("Location: index.php?nav=".$whateverpageyouwerebrowsingbefore
// $whateverpageyouwerebrowsingbefore would be something like /account/, /main/ or whatever

It's not much different than storing in a cookie the previous page, but it still need to be sanitized/validated against a list of permitted/allowed urls (or uri segments) you can include an associative array in all your page which maps your "route" to the correct redirect page. As for storing session information in a cookie : bad idea imo you should always store unimportant information in a cookie, even if it's encrypted, session are much more secure in this regard (even though you have to protect your app from session fixation vulnerabilities, but any serious dev will always do that unless they don't use sessions).

hmmm, i see

well i'm currently trying to set up a sessions table in my database to store the user sessions. try to be a little more secure that way, when I finish my site i'll look into extreme security measures and how to implements them. but for now i get a headeache thinking that far ahead or how more complicated things will be when i need to learn them.

  • 0

Securing a webapp/website isn't that difficult, you have ready to use libraries that can take care of it (somehow it's not automatic though, and for learning purpose anything "automatic" is evil).

The 4 most important things to recall when making a webapp are : XSS, XSRF (or CSRF), Session Fixations and SQL injection, xss is a matter of removing ability to run (mostly) any client code from your app :

Say you have a comment section somewhere in your code and it's to prevent people from injecting JS so that if someone hits the page they won't have spy scripts gathering your users session (for example).

CSRF/XSRF (Cross site request forgery) is to protect your admin functions, they should be built so that accessing them requires double authentication or in a separate process altogether, it's the trickier thing to protect.

Session fixations, well it's to prevent people to catch your session for one (through XSS usually) and access your website without even have to log in, there are a couple of ways to deal with that (special handshake at login, then stored in the DB ; the handshake is compiled and compared to the value stored in the DB each time a page is loaded, if the handshake is different, mostlikely to happen if someone got a session by vile means => logout/boot the user. Note that regarding session fixations the more restrictive you get the more likely you may kick legit users from accessing your applications. Things like transparent proxies, people behind nat etc etc... You will have to find the correct mix !. Also as you are using php, there is a server.ini settings that do not allow session information to be used as a query string (it disables the global variable $SSID if i recall)

And lastly Sql injection, (this is where validation comes in to play 99% of the time) attack vectors are most of the time forms/query strings/client cookies, validation should be done with anything that acts as an input, hopefully php has a bunch of tools that will help escape your sql commands.

But even if you master all of this and know how to protect your application, the number one flaw in your app will always be the dev, it's just a matter of "forgetting" to validate an input, or having a logic error in the code that will allow bad doers to f*ck around with your web app.

Edit: Fixed somethings that didn't make any sense, English is not my mother tongue.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • RIP Prince... for over 50 years you entertained us, brought us musicians that wowed the masses... you brought us into your home, your life and your loving insanity for life itself. You'll never be truly gone, because you'll be with us for the rest of our own lives.
    • This is why you NEVER use AI for development unless you are intelligent enough to know what it is doing.   100% the developer's fault.
    • im an MS fanboy and even this is hilarious to me... so many issues with 24h2, how can MS say this with a straight face?
    • Every vendor does this. Its just software dev. Do you release a current set or fixes or wait for them all? What if those fixes are taking really long?
    • Google Drive videos finally get thumbnail previews, but there's a big caveat by Usama Jawad Google Drive is a pretty decent cloud storage solution, especially if you're well-invested in Google's ecosystem. If you use an Android phone, you've probably used Google Drive to store your media content, emails, and WhatsApp backups. Just a couple of weeks ago, Google announced a UI revamp for its desktop sync client for Drive, and while it has announced a much smaller feature today, it's definitely quite handy. Videos stored on Google Drive are finally getting thumbnail previews. This means that if you hover your mouse over the progress bar of a video, you'll see a thumbnail for that time frame, just like YouTube. And similar to YouTube, you'll also be able to drag your cursor (or finger, depending upon your input mechanism) to scrub through the video while seeing thumbnail previews. This is a very useful capability that feels long overdue. When trying to locate a specific scene in a video, you no longer need to guess the approximate time, you can simply use thumbnail previews to sift through the video and reach your desired frame. There is a big caveat, though. Thumbnail previews in Google Drive videos are just available for newly uploaded content. There is no way to leverage the feature on the videos currently present in your Drive library. If you have turned on automatic backups to Drive through your Android phone or are just a Drive user in general, you likely have hundreds, if not thousands, of videos in your library. However, there is no way to enable thumbnail previews on any of them. In terms of rollout, this capability is now being made available to all Google Workspace customers, Google Workspace Individual subscribers, and personal Google accounts over the next few days. There is no way for Google Workspace admins to disable the feature from their side.
  • Recent Achievements

    • Week One Done
      SmileWorks Dental earned a badge
      Week One Done
    • Community Regular
      vZeroG went up a rank
      Community Regular
    • Collaborator
      Snake Doc earned a badge
      Collaborator
    • Week One Done
      Snake Doc earned a badge
      Week One Done
    • One Month Later
      Johnny Mrkvička earned a badge
      One Month Later
  • Popular Contributors

    1. 1
      +primortal
      583
    2. 2
      Michael Scrip
      199
    3. 3
      ATLien_0
      196
    4. 4
      +FloatingFatMan
      129
    5. 5
      Xenon
      123
  • Tell a friend

    Love Neowin? Tell a friend!