2016-09-15 44 views
0

所以我的問題是,如果我包含一個PHP文件,主要的PHP將是路徑。我無法描述得很好,所以讓我告訴你一些易於理解的代碼:PHP是指沒有DOCUMENT_ROOT的文件

這是我的網站:

本地主機/ mysite的/ index.php文件

<?php 
    include('common/sayHello.php'); 
?> 

我有一個管理員文件夾

本地主機/ mysite的/管理/ index.php文件

我已經得到了一些常見的文件

本地主機/ mysite的/通用/ sayHello.php

<?php 
    $text = file_get_contents(helloText.txt); 
    echo($text); 
?> 

localhost/mysite/common/helloText.txt

Hey! How you doing? 

但它不起作用。主要的「mysite/index.php」將尋找「mysite/helloText.txt」,而「mysite/admin/index.php」將尋找「mysite/admin/helloText.txt」。

我可以正確引用helloText文件,而不使用DOCUMENT_ROOT嗎?有沒有辦法在不改變url路徑的情況下包含文件?

你可能會說,我應該用一個 「/」 前 「通用/ helloText.txt」,但後來它會尋找本地主機/普通/ helloText.txt以代替localhost/mysite的/ ...

+3

所以使用'/ mysite/common/helloText.txt'。 – Barmar

+0

如果你不想硬編碼完整路徑,爲什麼你不想使用'DOCUMENT_ROOT'?這正是它的目的。 – Barmar

+0

@Barmar,但我也想在網絡上使用它..所以,如果我上傳最終版本(mysite.com/),那麼它會尋找(mysite.com/mysite/common ..).. –

回答

0

爲此我通常定義我的配置兩個常量:

define('PATH_ROOT', '/var/www/vhosts/example.com/app/'); 
define('HTTP_ROOT', 'http://example.com/'); 

所以,現在我可以很容易地在應用程序中使用PATH_ROOT定義絕對路徑,並與HTTP_ROOT在網站內。

然後我們有類似:

$myFile = 'some/path/foo.txt'; 
// write file to: /var/www/vhosts/example.com/app/some/path/foo.txt 
file_put_contents('Hello world!', PATH_ROOT . $myFile); 
// generate link to: http://example.com/some/path/foo.txt 
sprintf('<a href="%s">Click me!</a>', HTTP_ROOT . $myFile); 

如果您的應用程序將所有你需要做的就是修改這兩個常量。