How to display same header and footer on different pages?

怎甘沉沦 提交于 2019-12-24 02:56:21

问题


I have header.php and footer.php files which I include in all of my pages. A sample page looks like this -

<?php include($_SERVER['DOCUMENT_ROOT'].'/header.php');?>

<div id="content">
...
</div> <!-- content -->

<?php include($_SERVER['DOCUMENT_ROOT'].'/footer.php') ?>

Although this works well on the server, but when I test pages locally [ xampp on Windows 7 ], I get the following error message instead of the header, similarly for the footer -

Warning: include(C:/xampp/htdocs/header.php) [function.include]: failed to open stream: No such file or directory in C:\xampp\htdocs\f\index.php on line 1

Warning: include() [function.include]: Failed opening 'C:/xampp/htdocs/header.php' for inclusion (include_path='.;C:\xampp\php\PEAR') in C:\xampp\htdocs\f\index.php on line 1

This makes testing very tedious as I have to upload to the server for every minor change.

Also, I dug around the WP code, and it uses a get-header() to display the header.php file. I could not completely understand the function. My site does not use WP.

What is the correct way for including header and footer files?


回答1:


It seems that $_SERVER['DOCUMENT_ROOT'] is pointing to C:\xampp\htdocs, while your scripts are at C:\xampp\htdocs\f\, check the value of $_SERVER['DOCUMENT_ROOT'] on your local environment.

edit:

<?php
$rootDir = "";
if(strpos($_SERVER['HTTP_HOST'],'localhost')===FALSE)
{
  //On Production
  $rootDir = $_SERVER['DOCUMENT_ROOT'];
}
else
{
  //On Dev server
  $rootDir = $_SERVER['DOCUMENT_ROOT'].'/f';
}

<?php include($rootDir.'/header.php');?>

<div id="content">
...
</div> <!-- content -->

<?php include($rootDir.'/footer.php') ?>


?>



回答2:


the correct way to include any file is the include() or require() function. Wordpress uses a get_header() function because the header is more then just 1 file, so they created a function for outputting it.

The problem you have seems to be a problem with the $_SERVER variable. It has been quite a long time since I've worked with PHP, but what I would advise you to do is just use relative paths. For example, if the header.php and footer.php files are in the same directory as your index.php, you can just do:

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

<div id="content">
...
</div> <!-- content -->

<?php include('footer.php') ?>



回答3:


Simple and useful way (I use this in my all projects):

// find Base path
define( 'BASE_PATH', dirname(__FILE__) );

// include files
include BASE_PATH . '/header.php';
include BASE_PATH . '/footer.php';


来源:https://stackoverflow.com/questions/8211009/how-to-display-same-header-and-footer-on-different-pages

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!