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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4871942/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:09:04  来源:igfitidea点击:

How to redirect to another page using PHP

php

提问by jasonaburton

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

采纳答案by ThiefMaster

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>

回答by Joe Meyer

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()header('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(),以及其他答案此时遗漏的一些潜在错误。

回答by Vishal Kumar

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

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

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

回答by Kiran Reddy

headerwon't work for all

header不会对所有人都有效

Use below simple code

使用下面的简单代码

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

回答by Minkiele

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.

回答by pt2ph8

Assuming you're using cookies for login, just call it after your setcookiecall -- 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

回答by initall

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.

如果登录有效,您将使用“header”功能重定向。

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

回答by Pir Fahim Shah

On click BUTTON action

单击按钮操作

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

回答by Alfred Wayne

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 [email protected]

回答by mcbeav

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