![](/img/trans.png)
[英]PHP include when a “root forward slash” precedes the included path like: “/folder/file.php”
[英]Functions stop working when file included with root path (leading slash)
我的根目錄中的PHP文件INCLUDE header.php。 Header.php包含functions.php。 我在一個子目錄中添加新頁面,所以我在header.php:CSS,菜單項和隨后的INCLUDE到functions.php的所有鏈接中添加了前導斜杠。 CSS和菜單項在此頁面上的子目錄中均能正常工作,但功能不起作用。 功能中沒有鏈接似乎需要帶有斜杠。
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中,那么somefile
將在/home/foo/path/somefile
。
../somefile
。 ..
是指當前工作目錄的PARENT目錄,因此,如果您在/home/foo
,則將在../somefile
中搜索為/home/somefile
。
請注意,您可以使用非理性的路徑,例如
/../../../../somefile
。 這將是可以接受的,但毫無意義,因為您都將路徑固定在文件系統的根目錄上,然后嘗試超過根目錄,這是不可能的。 該路徑等效於/somefile
。
就是這樣,您知道,如果您要擁有要請求的php頁面,並且自己也請求其他頁面,那么使用require_once
而不是include
可能是有益的。 這將使所有包含的頁面都不重復自己,你不必擔心不小心包含一些東西。
話雖如此...當您在根目錄中請求頁面時,它將在根目錄中請求header.php,而該請求又將在根目錄中請求functions.php。 但是,如果你從子目錄請求, ../header.php
header.php將引用根目錄中的header.php,但是整個文件將被包含,然后它的子頁面中的php頁面最終試圖包含/functions.php
。 它需要請求../functions.php
,但這將導致根目錄中的所有內容停止工作。
我建議在header.php中沿$root = $_SERVER['DOCUMENT_ROOT'];
的行設置一個變量$root = $_SERVER['DOCUMENT_ROOT'];
然后,header.php中的所有include應該類似於include($root."/functions.php");
$_SERVER['DOCUMENT_ROOT']
將為您提供根目錄的網址,無論您在何處請求header.php,都可以確保您引用正確的位置。
Include
和Require
字面上將代碼拉入執行文件中,因此需要注意的一件事是子目錄中的文件是從工作目錄運行的。
例:
|-templates-|-header.php
Docroot--|
|-inc-|-functions.php
|
|-index.php
的index.php
<?php
include 'template/header.php';
...
?>
模板/ header.php文件
<?php
include 'inc/functions.php';
...
?>
因為由於包含原因,正在從docroot執行header.php代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.