절대 경로가 필요한 PHP 파일을 포함하는 방법은 무엇입니까?
다음과 같은 디렉토리 구조가 있습니다.
script.php
inc / include1.php
inc / include2.phpobjects / object1.php
objects / object2.phpsoap / soap.php
이제이 개체를 script.php
및 에서 모두 사용 하고 /soap/soap.php
이동할 수 있지만 특정 이유로 이와 같은 디렉터리 구조를 원합니다. 실행할 때 script.php
경로가 포함 inc/include.php
하고 실행할 때 /soap/soap.php
그건 ../inc
절대 경로 작업, /mnt/webdev/[project name]/inc/include1.php...
하지만 내가 다른 위치로 디렉토리를 이동할 경우는 추한 솔루션입니다.
따라서 상대 경로를 사용하는 방법이나 프로그래밍 방식으로 "/mnt/webdev/[project name]/"
?
이것은 작동합니다
$root = realpath($_SERVER["DOCUMENT_ROOT"]);
include "$root/inc/include1.php";
편집 : aussieviking에 의해 개선 추가
상대 경로를 사용할 수 있습니다. 시도해보십시오 __FILE__
. 이것은 항상 스크립트의 경로 / 파일 이름을 반환하는 PHP 상수입니다. 따라서에서 soap.php
다음을 수행 할 수 있습니다.
include dirname(__FILE__).'/../inc/include.php';
파일의 전체 경로 및 파일 이름입니다. 포함 내에서 사용되는 경우 포함 된 파일의 이름이 반환됩니다. PHP 4.0.2부터는
__FILE__
항상 심볼릭 링크가 해결 된 절대 경로를 포함하지만 이전 버전에서는 일부 상황에서 상대 경로를 포함했습니다. (출처)
또 다른 해결책은 httpd.conf 또는 .htaccess 파일에 포함 경로 를 설정하는 것 입니다.
http://au.php.net/reserved.variables를 살펴보십시오.
찾고있는 변수는 다음과 같습니다. $_SERVER["DOCUMENT_ROOT"]
프로젝트의 루트 디렉토리 경로로 상수를 정의한 다음 경로의 시작 부분에 넣을 수 있습니다.
포함 할 필요가 전혀없는이를 처리하는 또 다른 방법은 자동로드 기능 을 사용하는 것 입니다. 스크립트에 "Just in Case"에 필요한 모든 것을 포함하면 성능이 저하 될 수 있습니다. 포함이 모든 클래스 또는 인터페이스 정의이고 필요할 때만로드하려는 경우 __autoload()
자체 코드로 함수를 오버로드 하여 적절한 클래스 파일을 찾고 호출 될 때만로드 할 수 있습니다. 다음은 매뉴얼의 예입니다.
function __autoload($class_name) {
require_once $class_name . '.php';
}
$obj = new MyClass1();
$obj2 = new MyClass2();
이에 따라 include_path 변수를 설정하는 한 클래스 파일을 다시 포함 할 필요가 없습니다.
Kevin과 관련된 또 다른 옵션은 use입니다 __FILE__
. 대신 내부에서 php 파일 이름을 바꿉니다.
<?php
$docRoot = str_replace($_SERVER['SCRIPT_NAME'], '', __FILE__);
require_once($docRoot . '/lib/include.php');
?>
나는 이것을 한동안 사용하고 있습니다. 유일한 문제는 때로는 가지고 있지 $_SERVER['SCRIPT_NAME']
않지만 때로는 비슷한 다른 변수가 있다는 것입니다.
나는 이것이 매우 잘 작동한다는 것을 알았습니다!
function findRoot() {
return(substr($_SERVER["SCRIPT_FILENAME"], 0, (stripos($_SERVER["SCRIPT_FILENAME"], $_SERVER["SCRIPT_NAME"])+1)));
}
사용하다:
<?php
function findRoot() {
return(substr($_SERVER["SCRIPT_FILENAME"], 0, (stripos($_SERVER["SCRIPT_FILENAME"], $_SERVER["SCRIPT_NAME"])+1)));
}
include(findRoot() . 'Post.php');
$posts = getPosts(findRoot() . 'posts_content');
include(findRoot() . 'includes/head.php');
for ($i=(sizeof($posts)-1); 0 <= $i; $i--) {
$posts[$i]->displayArticle();
}
include(findRoot() . 'includes/footer.php');
?>
가장 좋은 방법은 포함을 PHP 포함 경로에 넣는 것입니다. 설정에 따라이를 수행하는 다양한 방법이 있습니다.
그런 다음 간단히 참조 할 수 있습니다.
require_once 'inc1.php';
포함 여부, 웹 액세스 가능 파일 또는 중첩 된 하위 디렉터리 수준에 관계없이 모든 파일 내부에서.
이를 통해 웹 서버 루트 외부에 포함 파일을 가질 수 있으며 이는 모범 사례입니다.
예 :
site directory
html (web root)
your web-accessible files
includes
your include files
또한 __autoload에서 클래스 파일의 지연로드를 확인하십시오.
http://www.google.com/search?q=setting+php+include+path
http://www.google.com/search?q=__autoload
require(str_repeat('../',(substr_count(getenv('SCRIPT_URL'),'/')-1))."/path/to/file.php");
I use this line of code. It goes back to the "top" of the site tree, then goes to the file desired.
For example, let's say i have this file tree:
domain.com/aaa/index.php
domain.com/bbb/ccc/ddd/index.php
domain.com/_resources/functions.php
I can include the functions.php file from wherever i am, just by copy pasting
require(str_repeat('../',(substr_count(getenv('SCRIPT_URL'),'/')-1))."/_resources/functions.php");
If you need to use this code many times, you may create a function that returns the str_repeat('../',(substr_count(getenv('SCRIPT_URL'),'/')-1))
part. Then just insert this function in the first file you include. I have an "initialize.php" file that i include at the very top of each php page and which contains this function. The next time i have to include files, i in fact just use the function (named path_back
):
require(path_back()."/_resources/another_php_file.php");
@Flubba, does this allow me to have folders inside my include directory? flat include directories give me nightmares. as the whole objects directory should be in the inc directory.
Oh yes, absolutely. So for example, we use a single layer of subfolders, generally:
require_once('library/string.class.php')
You need to be careful with relying on the include path too much in really high traffic sites, because php has to hunt through the current directory and then all the directories on the include path in order to see if your file is there and this can slow things up if you're getting hammered.
So for example if you're doing MVC, you'd put the path to your application directoy in the include path and then specify refer to things in the form
'model/user.class'
'controllers/front.php'
or whatever.
But generally speaking, it just lets you work with really short paths in your PHP that will work from anywhere and it's a lot easier to read than all that realpath document root malarkey.
The benefit of those script-based alternatives others have suggested is they work anywhere, even on shared boxes; setting the include path requires a little more thought and effort but as I mentioned lets you start using __autoload which just the coolest.
If you are going to include specific path in most of the files in your application, create a Global variable to your root folder.
define("APPLICATION_PATH", realpath(dirname(__FILE__) . '/../app'));
or
define("APPLICATION_PATH", realpath(DIR(__FILE__) . '/../app'));
Now this Global variable "APPLICATION_PATH" can be used to include all the files instead of calling realpath() everytime you include a new file.
EX:
include(APPLICATION_PATH ."/config/config.ini";
Hope it helps ;-)
참고URL : https://stackoverflow.com/questions/4369/how-to-include-php-files-that-require-an-absolute-path
'IT story' 카테고리의 다른 글
JavaScript 이외의 다른 언어가 중괄호 시작 위치 (같은 줄과 다음 줄)에 차이가 있습니까? (0) | 2020.09.03 |
---|---|
angularjs에서 이벤트를 트리거 한 요소에 액세스하는 방법은 무엇입니까? (0) | 2020.09.03 |
Python-목록을 함수 매개 변수로 사용 (0) | 2020.09.02 |
마우스 휠을 사용할 때 JScrollPane에서 스크롤 속도를 높이는 방법은 무엇입니까? (0) | 2020.09.02 |
grep을 사용하여 줄 번호 만보고 (0) | 2020.09.02 |