尝试使用 `DOCUMENT_ROOT 将它们包含在您的 PHP 文件中,即:
include($_SERVER['DOCUMENT_ROOT']."folder/header.php");
这假设,在浏览器中查看时,header.php 可以通过 http://127.0.0.1/folder/header.php 找到
对于其他文件,例如 CSS、Javascript,您可以按如下方式定义位置:
define("SCRIPTS_URL", "http://127.0.0.1/_scripts/");
在你的 header.php 文件中包含上述内容,并确保在调用实际的 html 标头之前包含 header.php,例如:
<?php
include($_SERVER['DOCUMENT_ROOT']."folder/header.php");
?>
<html>
<link rel="stylesheet" type="text/css" href="<?php echo SCRIPTS_URL; ?>stylesheet.css">
... etc etc ...
您可以进一步组合define并建立目录部分,例如:
$project = "project_x";
include($_SERVER['DOCUMENT_ROOT'].$project."/header.php");
define("SCRIPTS_URL", "http://127.0.0.1/".$project."/_scripts/");
如果你像上面那样做,那么你只需要改变项目变量,如果你看到...
更新
下面是 index.php:
<?php
// Make the header relative to index.php (as we don't know the project) - assume header is located at /_template/header.php and this file is located at /index.php [if, in future you have /content/index.php - then the below would be ../_template/header.php, etc]
if(file_exists("_template/header.php")){
include_once("_template/header.php");
} else {
die('Fatal error - no header found');
}
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="<?php echo BASE_URL; ?>styles/stylesheet.css">
</head>
<body>
// Content goes here
</body>
</html>
<?php
if(file_exists(ROOTPATH."_template/footer.php")){
include_once(ROOTPATH."_template/footer.php");
}
?>
还有header.php:
<?php
define("PROJECT_NAME", "project_x");
define("ROOTPATH", $_SERVER['DOCUMENT_ROOT'].PROJECT_NAME."/");
define("BASE_URL", "http://".$_SERVER['SERVER_NAME']."/".PROJECT_NAME."/"); // $_SERVER['SERVER_NAME'] automatically puts 'localhost' or the domain name in automatically
?>
如您所见 - 所有内容都在此头文件中定义,当它包含在 index.php 中时 - index.php 可以访问这些定义,就像在定义完成后包含的任何其他文件一样(请注意您不能覆盖一个定义,也不能两次定义相同的定义。