如何使用PHP重定向到另一个页面

时间:2022-11-29 23:11:33

I am 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).

我正在建立一个包含登录页面的网站。我需要在用户成功登录后将用户重定向到他们的个人资料页面,但我不知道如何在PHP中这样做(这是我的第一个网站)。

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.

我已经搜索过互联网,并且被告知header()函数应该可以解决这个问题,但只有在我使用它之前没有输出任何信息时它才会起作用。

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

那就是问题所在。我输出了一堆信息(包括HTML来构建登录页面本身)。

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

编辑:这是我的整个login.php页面

<?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;
    }
}
?>

11 个解决方案

#1


16  

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?

那就是问题所在。我输出了一堆信息(包括HTML来构建登录页面本身)。那么如何将用户从一个页面重定向到另一个页面呢?

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).

这意味着您的应用程序设计非常糟糕。在业务逻辑运行时,您不应该执行输出。使用模板引擎(如Smarty)或使用输出缓冲来快速修复它。

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

另一种选择(虽然不是很好!)会输出JavaScript来重定向:

<script type="text/javascript">location.href = 'newurl';</script>

#2


18  

You could use a function similar to:

您可以使用类似于以下的功能:

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

Worth noting, you should always use either ob_flush() or ob_start() at the beginning of your header('location: ...'); functions, and you should always follow them with a die() or exit() function to prevent further code execution.

值得注意的是,你应该总是在标题的开头使用ob_flush()或ob_start()('location:...');函数,你应该始终使用die()或exit()函数跟随它们,以防止进一步的代码执行。

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

这是比任何其他答案提到的更详细的指南: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.

本指南包含在重定向中使用die()/ exit()函数的原因,以及何时使用ob_flush()vs ob_start(),以及其他人在此时回答的一些潜在错误。

#3


11  

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

您可以有条件地重定向到php文件中的某个页面....

if {
//You need to redirect
header("Location: http://www.yourwebsite.com/user.php"); /* Redirect browser */
exit();
 }
else{
// do some
}

#4


3  

header won't work for all

标题不适用于所有人

Use below simple code

使用以下简单代码

<?php
        echo "<script> location.href='new_url'; </script>";
        exit;
?>

#5


2  

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.

假设你使用cookie进行登录,只需在你的setcookie调用之后调用它 - 毕竟,你必须在任何输出之前调用它。

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

#6


2  

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.

你可以使用ob_start();在发送任何输出之前。这将告诉PHP将所有输出保留在缓冲区中,直到脚本执行结束,因此您仍然可以更改标头。

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.

通常我不使用输出缓冲,对于简单的项目,我将所有逻辑保留在脚本的第一部分,然后输出所有HTML。

#7


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.

即使您使用“ob_start()”,有时也会错过一个导致输出的空白。但是,您将在错误日志中看到一条语句。

<?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();
?>

#8


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');

#9


0  

On click BUTTON action

单击BUTTON操作

   if(isset($_POST['save_btn']))
    {
        //write some of your code here, if necessary
        echo'<script> window.location="B.php"; </script> ';
     }

#10


0  

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

#11


0  

----------


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

?>


----------

#1


16  

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?

那就是问题所在。我输出了一堆信息(包括HTML来构建登录页面本身)。那么如何将用户从一个页面重定向到另一个页面呢?

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).

这意味着您的应用程序设计非常糟糕。在业务逻辑运行时,您不应该执行输出。使用模板引擎(如Smarty)或使用输出缓冲来快速修复它。

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

另一种选择(虽然不是很好!)会输出JavaScript来重定向:

<script type="text/javascript">location.href = 'newurl';</script>

#2


18  

You could use a function similar to:

您可以使用类似于以下的功能:

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

Worth noting, you should always use either ob_flush() or ob_start() at the beginning of your header('location: ...'); functions, and you should always follow them with a die() or exit() function to prevent further code execution.

值得注意的是,你应该总是在标题的开头使用ob_flush()或ob_start()('location:...');函数,你应该始终使用die()或exit()函数跟随它们,以防止进一步的代码执行。

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

这是比任何其他答案提到的更详细的指南: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.

本指南包含在重定向中使用die()/ exit()函数的原因,以及何时使用ob_flush()vs ob_start(),以及其他人在此时回答的一些潜在错误。

#3


11  

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

您可以有条件地重定向到php文件中的某个页面....

if {
//You need to redirect
header("Location: http://www.yourwebsite.com/user.php"); /* Redirect browser */
exit();
 }
else{
// do some
}

#4


3  

header won't work for all

标题不适用于所有人

Use below simple code

使用以下简单代码

<?php
        echo "<script> location.href='new_url'; </script>";
        exit;
?>

#5


2  

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.

假设你使用cookie进行登录,只需在你的setcookie调用之后调用它 - 毕竟,你必须在任何输出之前调用它。

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

#6


2  

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.

你可以使用ob_start();在发送任何输出之前。这将告诉PHP将所有输出保留在缓冲区中,直到脚本执行结束,因此您仍然可以更改标头。

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.

通常我不使用输出缓冲,对于简单的项目,我将所有逻辑保留在脚本的第一部分,然后输出所有HTML。

#7


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.

即使您使用“ob_start()”,有时也会错过一个导致输出的空白。但是,您将在错误日志中看到一条语句。

<?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();
?>

#8


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');

#9


0  

On click BUTTON action

单击BUTTON操作

   if(isset($_POST['save_btn']))
    {
        //write some of your code here, if necessary
        echo'<script> window.location="B.php"; </script> ';
     }

#10


0  

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

#11


0  

----------


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

?>


----------