[英]How can i Include a php file in a directory which contain include('xyz.php'); from another directory?
[英]php include file from another directory
這是一個結構示例:
/main
/css
style.css
/include
article1.php
article2.php
header.php
index.php
在我的header.php中,我有以下css代碼:
<link rel="stylesheet" type="text/css" href="css/style.css" />
並且,例如,在我的index.php中,我將以下內容作為第一行:
<?php include 'header.php'; ?>
現在,一切都很好。 接下來,我將在article1.php文件中插入以下代碼:
<?php include '../header.php'; ?>
內容(菜單和其他html)正確顯示,但CSS根本不會顯示/識別。 基本上發生的事情是包含頭文件但服務器不尊重目錄父項。 為了正確顯示CSS,我必須將CSS的link rel
更改為../css/style.css
,但如果我這樣做,則無法對位於主目錄中的文件進行操作。
我希望我能清楚地解決問題。 我究竟做錯了什么? 如何包含來自不同目錄的文件並保留其中的鏈接?
在站點的<head>
部分中,插入帶有href
屬性的<base>
元素 。 將href
屬性設置為您網站的基本URL,所有相關請求將通過該基本URL發送。
<base href="http://my-website-url.com/" />
<link rel="stylesheet" type="text/css" href="css/style.css" />
使用正確設置的base
標記,用戶的瀏覽器將嘗試從URL http://my-website-url.com/css/style.css
加載樣式表。
注意:這不僅會影響樣式表,還會影響文檔中的所有相對鏈接。
它與路徑的工作方式有關。 我建議盡可能從doc root中獲取路徑。
<?php include( $_SERVER['DOCUMENT_ROOT'] . '/header.php' ); ?>
這將適用於您的任何文件。
而不是使用相對路徑:
href="css/style.css"
使用來自webroot的絕對路徑:
href="/css/style.css"
您應該從根目錄中包含您的css文件。 所以/css/style.css所以它總是從根開始然后從那里開始。 我認為應該在所有情況下解決你的問題。
首先,問題是你的CSS文件鏈接是錯誤的。 最好的辦法是從頁面查看HTML(視圖源)的輸出。 所以讓我們分解它(形式index.php):
Index.php
位於domain.tld/index.php
。 您的css文件位於domain.tld/css/*
。 查看索引文件時,標題是
<link rel="stylesheet" type="text/css" href="css/style.css" />
這是有效的,因為您位於目錄(或根目錄)的頂部,並且相對於此目錄建立了鏈接。 現在當你進入domain.tld/include/article1.php
,你不再是根。 它試圖訪問:
domain.tld/include/css/style.css
這意味着您必須構建完整鏈接或更改您的親戚。 CSS以來的簡單方法就是使用以下內容
<link rel="stylesheet" type="text/css" href="/css/style.css" />
^
這意味着它將查看css目錄的域的根,如domain.tld/css/styles.css
。 如果您的頂級目錄是/main
,請使用/main/css/styles.css
我可以解釋一下你的問題以及如何解決它。
php中的include包含在C中。當您包含將頁面內容復制/粘貼到第一個頁面時的頁面。
所以,有兩個文件:
include.php
<?php
$var = 'PHP';
?>
main.php
<?php
include 'include.php';
echo $var; // affiche 'PHP'
?>
當您請求“main.php”頁面時,您將獲得以下信息:
<?php
$var = 'PHP';
echo $var; // affiche 'PHP'
?>
因此,如果您需要在頁面中包含元素。 你有兩個選擇:
1.絕對路徑(更好的方式)
而不是使用相對路徑,使用絕對路徑。 這種方式允許您在不使用當前路徑的情況下包含來自任何地方的文件。
變量
您可以使用包含存儲庫/網站根目錄的相對路徑的變量。 因此,每次必須包含頁面或創建一個頁面時,您必須按如下方式定義變量:
include.php
<?php
$var = 'PHP';
echo "<link rel=\"stylesheet\" type=\"text/css\" href=\"".$currentPath."css/style.css\" />";
?>
main.php
<?php
# path to the root of the website
$currentPath = "../";
include 'include.php';
echo $var; // affiche 'PHP'
?>
要了解有關包含的更多信息, 請參閱此頁面
你有兩個選擇
即。
<link rel="stylesheet" type="text/css" href="<?=$path ?>css/style.css" />
和
$path = "../";
include "header.php";
或2.您使用文件的絕對路徑
<link rel="stylesheet" type="text/css" href="/css/style.css" />
使用相對包含來自已被稱為包含的包含始終是一個問題,每次指定相對位置時,請替換您的
../some_directory/some_file.php
同
dirname(dirname(__FILE__)) . '/some_directory/some_file.php'
dirname(__FILE__)
是當前目錄。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.