使用include()后使用header()重定向

时间:2014-02-02 18:03:30

标签: php redirect

我的页面结构如下,我遇到了重定向工作的问题。此页面从URL获取ID并在查询中使用它。如果没有匹配项,只需重定向到另一个页面。

由于包含,我收到“标头已发送错误”。无论如何,我需要包括在那里。如果查询结果为空,我可以采用不同的方式进行重定向吗?

include('somepage.php');

$id = $_GET['id'];
$query = mysql_query("My query is here");

if(mysql_num_rows($query)==0) { header('Location:htp://example.com'); }

我尝试过使用exit();和各种停止处理功能。

somepage.php:

<html>
<head>
(standard html)
include('sql-connect.php');
</head>

<body>
(code to format the header portion of the site)

4 个答案:

答案 0 :(得分:1)

您可以将ob_start()放在文件的开头,这样看起来像这样:

<?php
ob_start();
include 'somepage.php';

$id = $_GET['id'];
$query = mysql_query("My query is here");

if(mysql_num_rows($query)==0) { header('Location:http://example.com'); }

此外,您可以回显html重定向:

<?php
if(mysql_num_rows($query)==0) { echo '<meta http-equiv="refresh" content="0; url=http://example.com/">'; die(); }

答案 1 :(得分:1)

您需要在文件开头添加ob_start(),如果这仍然无效,那么您还需要添加ob_flush();以完全清除旧标头。

    flush(); // Flush the buffer
    ob_flush();
    header("Location: http://example.com");

答案 2 :(得分:0)

结账后你可能有一个空行?&gt;这将导致一些文字空格作为输出发送,从而阻止您进行后续标题调用。请注意,离开收盘是否合法?&gt;关闭包含文件,这是避免此问题的有用习惯。

ob_start()可能会解决您的问题。

<html>
<?php
/* This will give an error. Note the output
 * above, which is before the header() call */
header('Location: http://www.example.com/');
exit;
?>

答案 3 :(得分:0)

“标头已发送错误”表示您的脚本(somepage.php)已将标头发送到浏览器,因此您无法更改这些标头并将用户重定向到其他网址。

最佳解决方案是在检查后移动“包含”操作符:

$id = $_GET['id'];
$query = mysql_query("My query is here");

if(mysql_num_rows($query)==0) { header('Location:http://example.com'); }

include('somepage.php');

此外,您可以阻止somepage.php向客户端发送任何数据。

第二个变体是使用函数ob_start(),ob_get_contents(),ob_end_clean():

ob_start();
include('somepage.php');

$id = $_GET['id'];
$query = mysql_query("My query is here");

if(mysql_num_rows($query)==0) { header('Location:http://example.com'); }
$content = ob_get_contents():
ob_end_clean();
echo $content;