2011-11-14 28 views
0

我在PHP嘗試,想知道我怎麼能在WordPress文件做這樣的事如何包含在PHP文件,還是尊重不同於相對鏈接包含的文件

if (site is wordpress) 
    include wordpress index.php; 

有一條線

require('./wp-blog-header.php');

這不會工作,因爲它拋出我找不到文件錯誤,它會工作,但如果我將其更改爲這個

require('wp-blog-header.php');

然後我沒有得到一個問題和頁面加載(以及一些擴展,因爲wp-blog-header.php加載在一些其他文件相對於wp-blog-header.php所以那些不要包含或加載)。

有什麼辦法可以讓PHP保持並尊重相關文件嗎?

編輯:包括我對我的問題

if ($app['framework']['type'] && $app['cms']['type']) {  
    echo "Only a Framework or CMS can be loaded at a time...";  
} else {  
    if (is_file("./app/" . $cfg['application']['name'] . "/index.php")) { 
     require_once "./app/" . $cfg['application']['name'] . "/index.php"; 
    } else {  
     if ($app['framework']['type']) {    
      echo "framework"; 
      //require_once "./app/" . $cfg['application']['name'] . "/" . $app['framework']['type'] . "/index.php";   
     } else if ($app['cms']['type']) {    
      if ($admin) { 
       require_once "./app/" . $cfg['application']['name'] . "/" . $app['cms']['type'] . "/wp-admin/index.php"; 
      } else {       
       $old_working_dir = getcwd(); // Remember where we are now. 
       chdir("./app/" . $cfg['application']['name'] . "/" . $app['cms']['type'] . "/");   // 'Go into' the Wordpress directory. 
       //include("index.php");   // Include the index.php file (no need for 'wordpress/') 
       chdir($old_working_dir); 
       require_once "index.php"; 
      } 
     } else {  
      echo "There is no index in your project directory, if your going to use a Framework or CMS please choose one from the following, thank you (list of cms's and frameworks)"; 
     } 
    }  
    exit; 
} 
+0

鏈接或文件名? –

+0

文件名,例如包括(「some-other-file.php」) – Eli

回答

1

您可以使用該功能getcwd()來獲取當前的工作目錄和chdir()來設置它的更好的上下文代碼。在你的情況下,它會是這個樣子:

$old_working_dir = getcwd(); // Remember where we are now. 
chdir("wordpress");   // 'Go into' the Wordpress directory. 
include("index.php");   // Include the index.php file (no need for 'wordpress/') 
chdir($old_working_dir);  // Go back to the previous directory. 

或者:

chdir("wordpress"); 
include("index.php"); 
chdir("../");     // Go back up one level. 
+0

哦,我從來沒有介紹過,讓我試試,我用我的實際代碼更新了這個問題, – Eli

+0

真的有效!謝謝 – Eli

+0

在你的發佈代碼中,你將工作目錄改回(用'chdir()')到原來的目錄,然後你使用' require'。切換這兩行,否則'chdir()'調用沒有用處,因爲您設置了它,然後立即恢復更改。 – RikkusRukkus

0

你最好定義一個包含路徑到應用程序的恆定和前置一個每一個包括你做的:

define("APP_PATH", "/var/www/app/"); 

... 

include(APP_PATH . 'foo/bar.php'); 
+0

與WordPress的問題是他們的常量定義爲他們的相關文件。 – Eli

0

你看過PHP的魔術常數__DIR__嗎?

該文件的目錄。如果在include中使用,則返回包含文件的目錄。這相當於dirname(FILE)。除非目錄名是根目錄,否則該目錄名沒有結尾斜槓。 (由在PHP 5.3.0)

如果您使用PHP的舊版本,你可以使用dirname(__FILE__)

這裏有一個小的使用例子:

/** 
* file hierarchy 
* ./index.php 
* ./foo/bar.php 
* ./foo/baz.php 
*/ 

// ./foo/bar.php 
include __DIR__.'baz.php'; 

// ./index.php 
include __DIR__.'/foo/bar.php'; 

,你可以現在包括index.php和理論上這些包括仍然應該工作。與其他答案相比,這也是一個不太冒犯的解決方案。

+0

問題是我不想更改wordpress使用的dirname()函數,而是將整個目錄加載到我的工作區中。所以url看起來像ww.foo.bar/index.php(它實際上會加載到www.foo.bar/wordpress/index.php) – Eli