[英]Php Get file from root dir to another dir
嗨,我是php編程的新手,學習這個我發現了一個小問題。 我有這樣的目錄:
c:/xampp/htdocs/
-practise
+ /css
+ /js
+ /images
- /extra
- /folder1
- / folder1_1
tst.php
index.php
navbar.php
about.php
blab.php
foo.php
lib.php
我創建了一個lib.php,其中該文件包含/css and /js
所有文件(jquery,w3.css等)。 我將這個文件添加到tst.php
例如include(../../../lib.php);
。 當我在瀏覽器中運行tst.php文件時,會執行lib.php的內容,但css and js
文件不會加載到瀏覽器中(在inspect元素->控制台中, 找不到錯誤文件 )。
我如何在tst.php和幾乎每個文件夾中使用我的lib.php ...?
我是否使用$_server['something']./lib.php...
?
這是我的lib.php
:
echo '<script src="js/browjs.js"></script> ';
echo '<link rel="stylesheet" type="text/css" href="css/poperi.css">';
echo '<link rel="stylesheet" href="css/w3.css">';
echo '<link rel="stylesheet" href="css/navigt.css">';
echo " this is content for check if lib.php is loaded or not";// this line show me in tst.php
我盡力解釋了我的問題,但我不知道您需要進一步了解這個問題的情況。
你可以嘗試
define( '_LIB_FILE_', $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . 'practise' . DIRECTORY_SEPARATOR . 'lib.php' );
並使用_LIB_FILE_
常量include_one _LIB_FILE_;
$_SERVER['DOCUMENT_ROOT']
是您的根目錄c:/xampp/htdocs/
您只需將子目錄附加到該目錄
LE:因此在您的lib.php中放入以下代碼行
<?php
$root = str_replace( '\\', '/', $_SERVER['DOCUMENT_ROOT'] );
$current_dir = str_replace( '\\', '/', dirname( __FILE__ ) );
$http_root = 'http://' . $_SERVER['HTTP_HOST'] . str_replace( $root, '', $current_dir ) . '/';
// echo $http_root; // this will let you see what is your current http path of lib.php ex. http://localhost/practise/
// next you include your code
// BEST PRACTICE short for multiple echos
echo '<script src="', $http_root, 'js/browjs.js"></script> ';
// you could do it with concatanation
echo '<link rel="stylesheet" type="text/css" href="' . $http_root . 'css/poperi.css">';
// string evaluation
echo "<link rel='stylesheet' href='{$http_root}css/w3.css'>";
// string evaluation with character escaping \"
echo "<link rel=\"stylesheet\" href=\"$http_rootcss/navigt.css\">";
echo " this is content for check if lib.php is loaded or not";
在您的tst.php中,您現在可以包括前面提到的代碼段,但是我將其轉換為變量
// this is called absolute path
$library_file = $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . 'practise' . DIRECTORY_SEPARATOR . 'lib.php';
include $library_file;
// or
// include( $library_file );
// and this is relative path. meaning the file relatively to your current file
// include '../../../lib.php';
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.