Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/239.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如果页面被访问,但不包括页面,如何重定向到另一个页面(PHP)_Php_Redirect_Include - Fatal编程技术网

如果页面被访问,但不包括页面,如何重定向到另一个页面(PHP)

如果页面被访问,但不包括页面,如何重定向到另一个页面(PHP),php,redirect,include,Php,Redirect,Include,我是一个PHP新手,试图自学,但现在我遇到了一个问题 我有一个index.php,它的功能如下: <!DOCTYPE html> <?php include("header.php"); ?> <html lang="de"> <head> <meta charset="utf-8"> <meta name="viewport"

我是一个PHP新手,试图自学,但现在我遇到了一个问题

我有一个index.php,它的功能如下:

<!DOCTYPE html>

<?php include("header.php"); ?>

<html lang="de">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Home</title>
  </head>
  <body>
    <?php printHeader(); ?>
  </body>
</html>
<?php function printHeader(){ ?>
    <p>foo</p>
<?php } ?>
}
和header.php,如下所示:

<!DOCTYPE html>

<?php include("header.php"); ?>

<html lang="de">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Home</title>
  </head>
  <body>
    <?php printHeader(); ?>
  </body>
</html>
<?php function printHeader(){ ?>
    <p>foo</p>
<?php } ?>
}

}
现在,我的问题是,当我访问index.php时,它工作正常,但是如果我访问header.php,我想重定向到index.php,而不是看到一个空白页面。如果我使用标题(…):

}
我当然会遇到一个错误(“页面没有正确重定向”),因为index.php会重定向到自身,从而启动一个循环

PHP中是否有任何类型的主函数,只在直接调用页面时调用,而不在仅包含页面时调用?或者还有其他解决办法吗


提前谢谢你!:3

如果希望仅在直接访问脚本时发生重定向,可以使用
$\u服务器[“请求URI”]
来确定

因此,对于标题,请从

<?php header("Location: index.php") ?>
<?php function printHeader(){ ?>
    <p>foo<?/p>
<?php } ?>
}

福
}


福
}
试试这个:
index.php

<!DOCTYPE html>
<html lang="en">

<head>
    <?php require_once dirname( __FILE__ ) . '/header.php'; ?>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Home</title>
</head>

<body>
    <?php printHeader(); ?>
</body>

</html>
header.php

<?php
/* -------------------- */
if ( $_SERVER['REQUEST_URI'] == '/header.php' ) {
    /* -------------------- */
    header('Location: ./');
}
/* -------------------- */
function printHeader () {
    /* -------------------- */
    echo '<p>foo</p>';
}
?>