• 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

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

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

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

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

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.

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

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

    • Oddly, there was a time that UFC games were culturally relevant, largely because of the graphics and gameplay that was different than the norm. But it seems like as the sport grew in popularity, gaming outlets stopped talking about the games.
    • Microsoft Edge 149.0.4022.69 by Razvan Serea Microsoft Edge is a super fast and secure web browser from Microsoft. It works on almost any device, including PCs, iPhones and Androids. It keeps you safe online, protects your privacy, and lets you browse the web quickly. You can even use it on all your devices and keep your browsing history and favorites synced up. Built on the same technology as Chrome, Microsoft Edge has additional built-in features like Startup boost and Sleeping tabs, which boost your browsing experience with world class performance and speed that are optimized to work best with Windows. Microsoft Edge security and privacy features such as Microsoft Defender SmartScreen, Password Monitor, InPrivate search, and Kids Mode help keep you and your loved ones protected and secure online. Microsoft Edge has features to keep both you and your family protected. Enable content filters and access activity reports with your Microsoft Family Safety account and experience a kid-friendly web with Kids Mode. The new Microsoft Edge is now compatible with your favorite extensions, so it’s easy to personalize your browsing experience. Microsoft Edge 149.0.4022.69 changelog: Fixed an issue that caused the Downloads dialog to continue displaying the "Keep/Delete" prompt for .rdp files after the download completed. Stable channel security updates are listed here. Download: Microsoft Edge (64-bit) | 193.0 MB (Freeware) Download: Microsoft Edge (32-bit) | 170.0 MB Download: Microsoft Edge (ARM64) | 188.0 MB View: Microsoft Edge Website | Release History Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Save 44% on Intuit QuickBooks Desktop Pro Plus 2024 (1 User for 1-Year) by Steven Parker Today's highlighted deal comes via our Apps + Software section of the Neowin Deals store, where for only a limited time, you can save 44% on Intuit QuickBooks Desktop Pro Plus 2024 (1 User + 1 Year) for Windows. Take control of your business finances with Intuit® QuickBooks® Desktop Pro Plus 2024 Lifetime Activation for Windows. This powerful accounting software simplifies bookkeeping, expense tracking, invoicing, and financial management—all in one intuitive platform. Designed for small business owners, freelancers, and accountants, QuickBooks® Desktop Pro Plus 2024 ensures accuracy, efficiency, and seamless transaction tracking. Stay organized, save time, and manage your finances with confidence—no subscriptions, just lifetime access! Financial and business management Comprehensive Financial Management: Gain access to a full suite of features designed to handle everything from creating invoices & managing expenses to generating reports and tracking sales. Enhanced Reporting Tools: Generate professional reports & insights to make informed financial decisions and help you stay ahead of your business goals. Job Costing: Track the profitability of specific jobs or projects. Fixed Asset Management: Track the depreciation & value of fixed assets. Customer & Vendor Management: Organize information, streamline communication & enhance customer relations. Sales Order Processing: Create & manage sales orders from start to finish. Purchase Order Processing: Create & manage purchase orders to streamline vendor payments. Improved Inventory Management: Enhanced features for tracking inventory levels & costs. Automation, integration, and support Enhanced Bank Feeds: Web Connect (manual QBO imports), works on all licenses for easier bank reconciliation Time Tracking: Track employee time to accurately calculate payroll and project costs Easy Data Import: Quickly transfer financial data from Excel or older QuickBooks® versions Why choose Intuit® QuickBooks® Desktop Pro Plus 2024? Effortless Installation: Quick and easy setup with step-by-step guidance. No Hidden Costs: One-time payment—no subscriptions or recurring fees. Direct Official Download: Access the software securely from the official QuickBooks® website. Stay Up to Date: Get the latest updates and features for optimal performance. Multilingual Support: Available in multiple languages to suit your needs. Lifetime Access: A one-time purchase means no ongoing costs. IMPORTANT: Cloud integrations (QuickBooks Payments, TurboTax, and Online logins) are NOT included. Good to know: Length of access: lifetime Redemption deadline: redeem your code within 30 days of purchase Access options: Windows Max number of device(s): 2 (for 1 user only and can't be used simultaneously) Version: 2024 (United States) 64-bit Available to both NEW and EXISTING users For US customers only Updates included An Intuit QuickBooks Desktop Pro Plus 2024 (1 User + 1-Year) for Windows: Lifetime License normally costs $536, but it can be yours for just $299.99 for a limited time, a saving of $236. There are also other plans available. For specifications, and license info please click the link below. Get Intuit QuickBooks Desktop Pro Plus 2024 for just $299.99 This is a time limited deal For US customers only. Support queries If you have queries or need support for any of the Neowin Deals, please use the contact form here. Neowin Deals are managed and sold by StackCommerce who represent Neowin on an affiliate basis. Why we post these deals We post these because we earn commission on each sale so as not to rely solely on advertising, which many of our readers block. It all helps toward paying staff reporters, servers and hosting costs. So for those that keep moaning and complaining, be thankful we're still online for you to even do that. Other ways to support Neowin Whitelist Neowin by not blocking our ads Create a free member account to see fewer ads Make a donation to support our day to day running costs Subscribe to Neowin - for $14 a year, or $28 a year for an ad-free experience Disclosure: Neowin benefits from revenue of each sale made through our branded deals site powered by StackCommerce.
    • AFAIK you shouldn't be getting a consent popup at all from Canada, so I think it is to do with a VPN or private/secure DNS.
    • From what I see it's only for Insider - preview builds. Not for everybody. So...
  • Recent Achievements

    • Week One Done
      agatameier earned a badge
      Week One Done
    • One Month Later
      agatameier earned a badge
      One Month Later
    • Week One Done
      ssd21345 earned a badge
      Week One Done
    • Contributor
      MarkHughes4096 went up a rank
      Contributor
    • Dedicated
      jordanspringer earned a badge
      Dedicated
  • Popular Contributors

    1. 1
      +primortal
      507
    2. 2
      +Edouard
      175
    3. 3
      PsYcHoKiLLa
      139
    4. 4
      ATLien_0
      90
    5. 5
      Steven P.
      76
  • Tell a friend

    Love Neowin? Tell a friend!