当文件包含根路径(前导斜杠)时,函数停止工作


Functions stop working when file included with root path (leading slash)

我的PHP文件在我的根目录INCLUDE header.PHP中。header.PHP INCLUDE functions.PHP。我在一个子目录中添加新页面,所以我在header.PHP中的所有链接上都添加了前导斜杠:CSS、菜单项和后续的INCLUDE to functions.PHP。函数中似乎没有需要前导斜杠的链接。

include和前导斜杠的组合是否需要修改函数

从根目录中的页面:

include('header.php');

从子目录中的页面:

include('/header.php');

来自header.php:

include('/functions.php');

以及不再工作的函数(从根目录或子目录中的页面调用):

function show_date($array_name){
if (date("Y F j",strtotime($array_name["exhibit_open"])) == date("Y F j",strtotime($array_name["exhibit_close"]))){
    echo date("F j, Y",strtotime($array_name["exhibit_open"]));
}
elseif (date("Y",strtotime($array_name["exhibit_open"])) != date("Y",strtotime($array_name["exhibit_close"]))) {
    $first_date_format = "F j, Y";
    echo date($first_date_format,strtotime($array_name["exhibit_open"])). " - ". date("F j, Y",strtotime($array_name["exhibit_close"]));
} elseif (date("F",strtotime($array_name["exhibit_open"])) != date("F",strtotime($array_name["exhibit_close"]))){
    $first_date_format = "F j";
    echo date($first_date_format,strtotime($array_name["exhibit_open"])). " - ". date("F j, Y",strtotime($array_name["exhibit_close"]));
} else {
    $first_date_format = "j";
    echo date("F j",strtotime($array_name["exhibit_open"])). " - ". date($first_date_format,strtotime($array_name["exhibit_close"])). ", ". date("Y",strtotime($array_name["exhibit_close"]));
}

}

标准路径101:

/path/somefile-前导/将此路径结构锚定在文件系统的ROOT,例如,它相当于C:'path'somefile

path/somefile-无前导/。操作系统将使用程序"当前工作"目录作为路径的基础,因此,如果您在/home/foo中的shell中,则将在/home/foo/path/somefile中搜索somefile

CCD_ 10。..指的是当前工作目录的PARENT目录,因此如果您在/home/foo中,则../somefile将被搜索为/home/somefile

注意,你可以有像这样的非感官路径

/../../../../somefile。这是可以接受的,但毫无意义,因为你们都将路径锚定在文件系统的根目录上,然后试图超越根目录,这是不可能的。该路径在操作上等效于/somefile

请注意,如果您要让请求的php页面本身也请求其他页面,那么使用require_once而不是include可能是有益的。这样一来,所包含的页面就不会重复,你也不必担心意外地包含多个页面。

话虽如此。。。当您在根目录中请求页面时,它会在根目录下请求header.php,而header.php又会在根路径下请求functions.php。但是,如果您从子目录中请求,../header.php将引用根目录中的header.php,但整个文件将被包括在内,然后子目录中的php页面最终试图包括/functions.php。它需要请求../functions.php,但这会导致根目录中的所有内容都停止工作。

我建议在header.php中按照$root = $_SERVER['DOCUMENT_ROOT'];的行设置一个变量。然后,header.php中的所有includes都应该像include($root."/functions.php"); 一样

$_SERVER['DOCUMENT_ROOT']将为您提供指向根的目标url,这将使您能够确保无论从哪里请求header.php,都引用了正确的位置。

IncludeRequire将代码拉入执行文件,因此需要注意的一点是,子目录中的文件是从工作目录运行的。

示例:

         |-templates-|-header.php
Docroot--|
         |-inc-|-functions.php
         |
         |-index.php

索引.php

<?php
include 'template/header.php';
...
?>

template/header.php

<?php
include 'inc/functions.php';
...
?>

因为header.php代码是由于include而从docroot执行的。