在使用输出缓冲写入后无法使用标头功能重定向

时间:2016-06-21 22:43:27

标签: php

我希望在五秒后重定向用户,这段小代码会在5秒后重定向。

   <?php
    ob_start();

    echo "Thank you for your input";
    header("Refresh: 5; url=http://www.google.com");
    ob_end_flush();
     ?>

但是当我尝试将它实现到我的应用程序中时,没有任何反应。这里标题功能不起作用。

<?php 

$name = "";
$email = "";
$subject = "";
$comments = "";
$nameError = "";
$emailError = "";
$subjectError = "";
$timestamp = date("Y-m-d H:i:s");
$x = 5;
$userIP = $_SERVER['REMOTE_ADDR'];
function filterData($data)  {
$data = mysql_real_escape_string($data);
return $data;
}
$connection = mysql_connect('----', '----', '-----'); 

$select_database = mysql_select_db("contact"); 

if ($_SERVER["REQUEST_METHOD"] == "POST") {
//handles the name 
$name = filterData($_POST["name"]);
if (empty($name)) {
$nameError = "please don't leave the name field blank";
}

//handles the email
$email = filterData($_POST["email"]);
if (empty($email)) {
$emailError = "please don't leave the email field blank";
}

//handles the subject
$subject = filterData($_POST["subject"]);
if (empty($subject)) {
$subjectError = "please don't leave this field blank";
}

$comments = filterData($_POST["comments"]);

}

$insertation = "INSERT INTO contactinfo (name, email, subject, date, comments, ip)
VALUES ('$name', '$email', '$subject', '$timestamp', '$comments', '$userIP')";

$insertationQuery = mysql_query($insertation, $connection);

ob_start();

echo "Thank you for your input";
header("Refresh: 5; url=http://www.google.com");
ob_end_flush();

?> 

我尝试将ob_start()和ob_end_flush()分别放在开头和结尾。但这似乎仍然无效。

1 个答案:

答案 0 :(得分:0)

必须先调用

header才能回显任何内容。请将echo放在header之后。

header("Refresh: 5; url=http://www.google.com");
echo "Thank you for your input";

http://php.net/manual/en/function.header.php#97114