为什么php头需要花费大量时间进行重定向


why php headers are getting huge time to redirect?

我正在用php和mysql开发一个非常简单的脚本。问题是php头重定向需要花费大量时间进行重定向。没有重定向脚本工作得很快。我使用php头重定向来删除兑现的表单数据,并将process.php重定向到根索引。。

这是我的index.php代码

<?php ob_start(); ?>
<html>
<head>
<title>myWall ~ V.02</title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
</head>
<body>
<?php
// import connect.php file.
require 'connect.php';
require 'form.php';
// checking form set || not && form empty || not.
if (isset($_POST['status'])){
    if (!empty($_POST['status'])){
        $status = nl2br(htmlentities($_POST['status']));
        // sql query string for insert a status to database.
        $insertAStatus = "INSERT INTO `database`.`table` (`id`, `status`) VALUES (NULL, '".$status."');";
        mysqli_query($con,$insertAStatus);
        //echo 'added a status';
        // redirecting to main root for clear form submitted data.
        header('location: ../mywall');
    } else {
        echo 'Please enter a status.<br>';
    }
} // end. if isset.
// getting number of rows in db.
$getNumRows = "SELECT * FROM `status`;";
$gotNumRows = mysqli_query($con,$getNumRows);
$numOfRows = mysqli_num_rows($gotNumRows);
if ($numOfRows != 0){
echo 'You have '.$numOfRows.' Status.';
} else {
return NULL;
}

// display data in database.
$getData = "SELECT * FROM `status` ORDER BY `status`.`id` DESC";
$dataFromDb = mysqli_query($con,$getData);

// display data through while loop.
while ($row = mysqli_fetch_array($dataFromDb,MYSQLI_ASSOC)){
echo "<div style='padding: 5px; background:#F1F1F1; margin: 5px;'>".$row['status']."<a style='float:right' href='process.php?delete=".$row['id']."'>[delete]</a><a style='float:right' href='#'>[edit]</a><div style='clear:both'></div></div>";
}
?>
</body>
</html>
<?php ob_end_flush(); ?>

这是我对上述脚本的在线演示

http://dzine.us/dev/mywall/

请注意,header()函数之后的代码仍在执行。这意味着,即使您想要重定向,查询仍然会被执行。

试着放一个骰子();或exit();页眉后的行("位置:…");

当您想要重定向时,这将停止执行其余代码。

header()函数会更改标头位置,但在执行完其余代码之前不会重定向。你可以这样做,使它立即重定向:

header("Location: ...");
exit(0); //This should come just after header statement.

这将在您需要时尽快重拨到另一个网页,因为代码的其余部分将不会执行。