User Redirect to another URL after PHP form post - suggestions on approach

gisvpn
gisvpn used Ask the Experts™
on
Hi,

Looking for best advice on how to redirect my page after the user had logged into the site.

I have a PHP form which is using the POST method to submit the details to the login page (called login.php) and connects to the mySQL database to authenticate. If the user successfully has entered the right information I have a link that will move them into a members page - i do this process via an IF....Else statement.

Instead of getting the user to actively click on then link to move them on, how would it best be done to automatically redirect the user to the next page (i.e., dashboard.php)? I was looking at the PHP header() function and a JavaScript window.location.replace option - wanted to get some opinions on here too on the simplest, universal way to do this?

Open to any options/suggestions; doesnt have to be PHP or JavaScript.

Thanks in advance.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2018
Distinguished Expert 2018
Commented:
If you're authenticating in PHP then use the header() function:

if ($authenticated) {
    header('Location: dashboard.php');
} else {
    header('Location: login.php');
}

Open in new window

Be aware though that the header call will only work if you haven't already sent output, so don't echo anything out before it - there are ways around this, but for now - just don't it :)

Author

Commented:
Ok thanks. Could I check what you mean by not already send an output ? I use various if statement to echo out messages if for example the password was incorrect
Most Valuable Expert 2018
Distinguished Expert 2018
Commented:
Basically, if you want to use header(), you can't echo anything out before making the call. Generally, all it takes is to think through your logic a little.

So, let's say you have a Form on the login.php page that POSTs back to itself. At the very top of that page you would have something like:

<?php
session_start();
if ($_POST['submit']) {
    // Let's check the login
    // connect to DB, and query the user

    if (TheyAreAuthenticed) {
        $_SESSION['user'] = "logged-in userName";
        header('Location: dashboard.php');
    } else {
        $error = "Could not authenticate you";
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>...</head>
<body>
    <?php if (isset($error)): ?>
    <div class="warnings">
        <?= $error; ?>
    </div>
    <?php endif; ?>

    <form method="post">
        ....

Open in new window

You can see from here that we can safely call our header() function, because we haven't output anything before it. If the user is not authenticated, the header() call is never made - the form loads up, and if an error has been set, it's displayed to the user.

FYI - Don't give out message like "Password Incorrect". If an attacker tries and gets a message saying that, they immediately know that the Username is correct ;)
Ensure you’re charging the right price for your IT

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

Most Valuable Expert 2017
Distinguished Expert 2018
Commented:
To add to Chris' statement there are two approaches to this
1. You POST a form to a script which then does a header('location: member.php');
2. You AJAX the login details to the server script and it sends back a status - based on that you do a window.location='member.php';

Which one you use depends on the overall strategy your application uses.

Personally I prefer the AJAX method as it means my authentication script only has to do authentication - not re-rendering the login page with error messages etc.

If you are going to do the POSTback method then I would use a redirect function

function redirect($url)
{
  if (!headers_sent()) {
    header("location: {$url}");
  }
  else {
      echo "<script>window.location = '{$url}';</script>
   }
}

Open in new window

This code will make sure your page redirects even if output has already been sent.

Author

Commented:
Hi - I have been doing a bit more research on the need and approach. I ended up just adding this to my IF....Else statement:

echo"<script> window.location.href = 'dashboard.php'; </script>";

Open in new window


Given where I was with the overall application it appears the easiest way to add. Is there anything you would call out with this approach :)?

Thanks for the note on the error out message related to the password too.
Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
JS is fine. The only thing I'd point out that if you're redirecting with JS, the page has to start loading in the browser in order to fire the <script> tag. With PHP's header() call the page never has to start loading before the redirect happens as it's called directly on the server. May not be an issue, but your user could potentially start downloading your HTML, JS Libraries, Stylesheets etc, before reaching your redirect script. You shouldn't notice any screen flicker, but it's something to be aware of.
Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
My preference is always header() - it is the cleaner approach. The redirect function was provided for those instances where your application design may make it difficult to determine if a redirect is needed before you start output. I try to limit use of ob_start() so this function is (in my view) a better compromise. Ultimately though I would look at my design and study MVC patterns to see how to structure my code so that the controller can make a redirect decision before it passes control to the view.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial