74

I'm building a website which includes a login page. I need to redirect the user to their profile page once they've logged in successfully, but I don't know how to do that in PHP (It's my first site).

I've searched the internet and have been told that the header() function should do the trick, but it will only work if I haven't outputted any information before using it.

That's the problem. I've outputted a bunch of information (Including the HTML to build the login page itself).

So how do I redirect the user from one page to the next?

What options do I have? Also, what is the best practice in these instances?


EDIT: Here's my entire login.php page:

<?php 

session_start(); 

echo "<!DOCTYPE html> 
  <html> 
     <head> 
        <meta charset='utf-8'> 
        <title>Sprout</title>
    <link rel='stylesheet' href='stylesheet.css' type='text/css'>
     </head>
 <body>
    <div class='box'>
    <form action='login.php' method='post'>
       Name<br /> <input type='text' name='username' class='form'/><br />
       Password<br /> <input type='password' name='password' class='form'/>
       <input type='submit' value='Login' class='button' />
    </form>
    </div>
 </body>
  </html>";

if ($_SERVER['REQUEST_METHOD'] == 'POST') 
{
    $username = $_POST["username"];
    $password = $_POST["password"];

    $dbhost = "localhost";
    $dbuser = "root";
    $dbpass = "root";

    $conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ("Error connecting to database");

    $dbname = "database";

    mysql_select_db($dbname);

    $query = "SELECT username FROM users WHERE username = '$username' AND password = '$password'";

    $result = mysql_query($query) or die ("Failed Query of " . $query);


    while($row = mysql_fetch_assoc($result))
    {
            $_SESSION["user"] = $username;
    }
}
?>
Or Assayag
  • 5,662
  • 13
  • 57
  • 93
jasonaburton
  • 2,941
  • 7
  • 34
  • 48
  • im a little confused here, basically, the header function is what your looking for, but i think you are using it wrong here, so the html page is the login page, and there is form for the user to log in, when you click submit, or login or whatever, what happens, where are you going? – mcbeav Feb 02 '11 at 07:53
  • the header function should be stuck in your login script. give up some code or more specifics so i can help you more. – mcbeav Feb 02 '11 at 07:55
  • btw, did you write the script to login or are you using a prebuilt one? it is important. – mcbeav Feb 02 '11 at 07:56
  • What are you using to build your site? Are you building a login script from scratch? – KyleWpppd Feb 02 '11 at 08:00
  • Question: what's the use of displaying stuff if your going to redirect it anyway? That's the reason why header location requires not to display anything before it, because they know it makes no sense. – gianebao Feb 02 '11 at 08:03
  • Yeah I'm building it from scratch. – jasonaburton Feb 02 '11 at 08:04
  • What I'm trying to do is log the user into the site. The user enters their info and logs in, then my script runs to make sure they are registered, then redirects them to their profile page. – jasonaburton Feb 02 '11 at 08:05
  • WHOA there... Shouldn't you be hashing that password before checking it against the database? And probably also sanitizing your data, so someone doesn't send you `$username; DROP TABLE users;` as their username? – KyleWpppd Feb 02 '11 at 08:06
  • I'll get to that eventually, I am just making a quick little login page to get me started. – jasonaburton Feb 02 '11 at 08:08

13 Answers13

70

You could use a function similar to:

function redirect($url) {
    header('Location: '.$url);
    die();
}

Worth noting, you should use a die() or exit() function to prevent further code execution.

Note that it just makes no sense to output large chunks of HTML if you are going to redirect. Therefore you have to move the form handling code above all HTML. As a side effect it will mitigate the notorious "Headers already sent" error.

Here's a more detailed guide than any of the other answers have mentioned: http://www.exchangecore.com/blog/how-redirect-using-php/

This guide includes reasons for using die() / exit() functions in your redirects, as well as when to use ob_flush() vs ob_start(), and some potential errors that the others answers have left out at this point.

Andrew T.
  • 70
  • 1
  • 6
Joe Meyer
  • 4,315
  • 20
  • 28
43

You can conditionally redirect to some page within a php file....

if (ConditionToRedirect){
  //You need to redirect
  header("Location: http://www.yourwebsite.com/user.php");
  exit();
 }
else{
  // do something
}
Vishal Kumar
  • 4,419
  • 1
  • 25
  • 31
37

That's the problem. I've outputted a bunch of information (including the HTML to build the login page itself). So how do I redirect the user from one page to the next?

This means your application design is pretty broken. You shouldn't be doing output while your business logic is running. Go an use a template engine (like Smarty) or quickfix it by using output buffering).

Another option (not a good one though!) would be outputting JavaScript to redirect:

<script type="text/javascript">location.href = 'newurl';</script>
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
  • What I have done is outputted all my HTML to build the login page, then my logic runs afterwards. It's just a form I created with a username and password field. The user enters it and clicks login, and I have a post back to the same login.php file, where I run the logic to see whether or not they are in fact a user. and then redirect them to their profile. If this isn't how I should structure it, then what's the best practice? – jasonaburton Feb 02 '11 at 08:02
  • 1
    here's some pseudocode: if(form submitted) { handle data and redirect+exit if successful } show form; if it has been submitted populate it with the submitted values – ThiefMaster Feb 02 '11 at 08:04
  • How do I redirect though? Since the form is echoed on the same page I cannot use header() – jasonaburton Feb 02 '11 at 08:07
  • 1
    What you suggested worked! Thanks. That's definitely a better way to go about it than what I was trying to hack together. – jasonaburton Feb 02 '11 at 08:16
20

header won't work for all

Use below simple code

<?php
        echo "<script> location.href='new_url'; </script>";
        exit;
?>
Kiran Reddy
  • 734
  • 12
  • 28
5

Assuming you're using cookies for login, just call it after your setcookie call -- after all, you must be calling that one before any output too.

Anyway in general you could check for the presence of your form's submit button name at the beginning of the script, do your logic, and then output stuff:

if(isset($_POST['mySubmit'])) {
    // the form was submitted

    // ...
    // perform your logic

    // redirect if login was successful
    header('Location: /somewhere');
}

// output your stuff here
ySgPjx
  • 10,165
  • 7
  • 61
  • 78
3

You could use ob_start(); before you send any output. This will tell to PHP to keep all the output in a buffer until the script execution ends, so you still can change the header.

Usually I don't use output buffering, for simple projects I keep all the logic on the first part of my script, then I output all HTML.

Minkiele
  • 1,260
  • 2
  • 19
  • 32
  • 1
    As ThiefMaster said, it is best to not output anything at all until very late in the process (and only if actually necessary) but output buffering is still good to ensure that really nothing is sent before all headers are out. You can even discard all output buffer content if you later discover some problem while generating your output using `ob_clean()` / `ob_end_clean()`. – Arc Feb 02 '11 at 08:16
  • Output buffering was going to be my second attempt but it's been figured out. Thanks for the help nonetheless! – jasonaburton Feb 02 '11 at 08:18
1
firstly create index.php page and just copy paste below code :-

<form name="frmUser" class="well login-form" id="form" method="post" action="login_check.php" onSubmit="return FormValidation()">
    <legend>
        <icon class="icon-circles"></icon>Restricted Area<icon class="icon-circles-reverse"></icon>
    </legend>
    <div class="control-group">
        <label class="control-label" for="inputPassword">Username</label>
        <div class="controls">
            <div class="input-prepend">
                <span class="add-on"><icon class="icon-user icon-cream"></icon> </span>
                <input class="input" type="text" name="username" id="username" placeholder="Username" />
            </div>
        </div>
    </div>
    <div class="control-group">
        <label class="control-label" for="inputPassword">Password</label>
        <div class="controls">
            <div class="input-prepend">
                <span class="add-on"><icon class="icon-password icon-cream"></icon>
                </span> <input class="input" type="password" name="password" id="password" value="" placeholder="Password" />
            </div>
        </div>
    </div>
    <div class="control-group signin">
        <div class="controls ">
            <input type="submit" class="btn btn-block" value="Submit" />
            <div class="clearfix">
                <span class="icon-forgot"></span><a href="#">forgot password</a>
            </div>
        </div>
    </div>
</form>



/*------------------after that ----------------------*/

create a login_check.php and just copy paste this below code :-

<?php
session_start();
include('conn.php');

<?php
/* Redirect browser */
header("location:index.php");

/* Make sure that code below does not get executed when we redirect. */
exit;
?>


<?php

if(count($_POST)>0)
{   

    $result = mysql_query("SELECT * FROM admin WHERE username='".$_POST["username"]."' and password = '".$_POST["password"]."'");
    $row  = mysql_fetch_array($result);

if(is_array($row)) 
{
    $_SESSION["user_id"] = $row[user_id];
    $_SESSION["username"] = $row[username];

    $session_register["user_id"] = $row[user_id];
    $session_register["username"] = $row[username];
} 
else 
{
   $_SESSION['msg']="Invalid Username or Password";
   header("location:index.php");
}
}

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

?>




/*-----------------------after that ----------------------*/


create a dashboard.php and copy paste this code in starting of dashboard.php



<?php
session_start();
include('conn.php');
include('check_session.php');
?>




/*-----------------------after that-----------------*/ 



create a check_session.php which check your session and copy paste this code :- 


<?php
    if($_SESSION["user_name"]) 
    {
?>
    Welcome <?php echo $_SESSION["user_name"]; ?>. Click here to <a href="logout.php" tite="Logout">Logout.</a>
<?php
    }
    else
    {
     header("location:index.php");
    }
?>





if you have any query so let me know on my mail id farjicompany@gmail.com
1

The simplest approach is that your script validates the form-posted login data "on top" of the script before any output.

If the login is valid you'll redirect using the "header" function.

Even if you use "ob_start()" it sometimes happens that you miss a single whitespace which results in output. But you will see a statement in your error logs then.

<?php
ob_start();
if (FORMPOST) {
    if (POSTED_DATA_VALID) {
        header("Location: https://www.yoursite.com/profile/");
        ob_end_flush();
        exit;
    }
}
/** YOUR LOGINBOX OUTPUT, ERROR MESSAGES ... **/
ob_end_flush();
?>
initall
  • 2,385
  • 19
  • 27
0

On click BUTTON action

   if(isset($_POST['save_btn']))
    {
        //write some of your code here, if necessary
        echo'<script> window.location="B.php"; </script> ';
     }
Pir Fahim Shah
  • 10,505
  • 1
  • 82
  • 81
0

----------


<?php
echo '<div style="text-align:center;padding-top:200px;">Go New Page</div>'; 
  $gourl='http://stackoverflow.com';
  echo '<META HTTP-EQUIV="Refresh" Content="2; URL='.$gourl.'">';    
  exit;

?>


----------
Waruna Manjula
  • 3,067
  • 1
  • 34
  • 33
0

Although not secure, (no offense or anything), just stick the header function after you set the session variable

 while($row = mysql_fetch_assoc($result))
    {
            $_SESSION["user"] = $username;
    }
header('Location: /profile.php');
mcbeav
  • 11,893
  • 19
  • 54
  • 84
  • this should work, it should only redirect if the query was performed. – mcbeav Feb 02 '11 at 08:11
  • None taken. I'm new at this. It's a learning experience for me. – jasonaburton Feb 02 '11 at 08:13
  • I've tried putting it after the session but the header function won't work after I've ouputted something on the page (the HTML). – jasonaburton Feb 02 '11 at 08:13
  • whoops, sorry, try sticking it outside of the loop, right after – mcbeav Feb 02 '11 at 08:14
  • while($row = mysql_fetch_assoc($result)) { $_SESSION["user"] = $username; } – mcbeav Feb 02 '11 at 08:15
  • sorry about that, try the edited one, sorry its late and im being sloppy. – mcbeav Feb 02 '11 at 08:16
  • My logic wasn't right. But I switched a few things around and it works now. – jasonaburton Feb 02 '11 at 08:17
  • if that doesn't work you have a couple different options, if the login page is the only thing on that page you could do something like, if(isset($_SESSION['user'])){ header('Location: /profile.php'); } or you could wrap it in a function and call it from outside of the page, i wouldn't recommend keeping your connection settings on the same page as the people will be using, you could save the function in another page and call it at the beginning of the page, ex: at the top of the login page, but you will have to rewrite the function a bit and call it – mcbeav Feb 02 '11 at 08:20
  • ah, k, sorry i couldn't help, i don't know if that is the script you will be using but you should look into php security, there are alot of ways to destroy your data from a form, or access the data from a form. always sanitize the input, prepared statements would be a smart idea. – mcbeav Feb 02 '11 at 08:21
  • Oh of course. I was just putting something quick together just to get me started. I'll be doing my research. – jasonaburton Feb 02 '11 at 08:23
  • right on, just want to make sure you do some research, just a major bummer losing all of your data or having someone mess with it. some things to look into are: salts, hashing, prepared statements, rainbow tables, form keys, and xss attacks. Just good to have the knowledge when creating a login system. – mcbeav Feb 02 '11 at 08:27
  • Thanks. I really appreciate that. I will look into those topics! – jasonaburton Feb 02 '11 at 08:29
0

Just like you used echo to print a webpage. You could use also do the same with redirecting.

print("<script type=\"text/javascript\">location.href=\"urlHere\"</script>")
0
<?php 
include("config.php");
 
 
$id=$_GET['id'];

include("config.php");
if($insert = mysqli_query($con,"update  consumer_closeconnection set close_status='Pending' where id="$id"  "))
            {
?>
<script>
    window.location.href='ConsumerCloseConnection.php';

</script>
<?php
            }
            else
            {
?>
<script>
     window.location.href='ConsumerCloseConnection.php';
</script>
<?php            
    }
?>      
TheFaultInOurStars
  • 3,464
  • 1
  • 8
  • 29
payal
  • 1