首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在使用include()之后使用header()重定向

在使用include()之后使用header()重定向
EN

Stack Overflow用户
提问于 2014-02-03 02:03:30
回答 4查看 1.7K关注 0票数 0

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

由于包含,我得到了"headers already error“。我需要include不管怎样都在那里。如果查询结果为空,有没有不同的重定向方法?

代码语言:javascript
复制
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:

代码语言:javascript
复制
<html>
<head>
(standard html)
include('sql-connect.php');
</head>

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

回答 4

Stack Overflow用户

回答已采纳

发布于 2014-02-03 02:08:38

您可以将ob_start()放在文件的开头,使其如下所示:

代码语言:javascript
复制
<?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重定向:

代码语言:javascript
复制
<?php
if(mysql_num_rows($query)==0) { echo '<meta http-equiv="refresh" content="0; url=http://example.com/">'; die(); }
票数 1
EN

Stack Overflow用户

发布于 2014-02-03 02:10:01

您需要在文件的开头添加ob_start(),如果此操作仍然不起作用,则还需要添加ob_flush();以完全清除旧的标头。

代码语言:javascript
复制
    flush(); // Flush the buffer
    ob_flush();
    header("Location: http://example.com");
票数 1
EN

Stack Overflow用户

发布于 2014-02-03 02:11:41

您可能在结束?>后有一个空行,这将导致一些文字空白作为输出发送,从而阻止您进行后续的头调用。请注意,在包含文件中保留关闭?>是合法的,这是避免此问题的一种有用的习惯用法。

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

代码语言:javascript
复制
<html>
<?php
/* This will give an error. Note the output
 * above, which is before the header() call */
header('Location: http://www.example.com/');
exit;
?>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21514160

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档