PHP include absolute path

百般思念 提交于 2019-11-27 09:03:49

You can't include php files relatively to your webroot that way, cause if you use the slash as first character, the reference will go much deeper than just your document root. So, instead of using your basepath, you could do something like this :

<?php 
   $path = $_SERVER['DOCUMENT_ROOT'];
   $path .= "/yourpath/yourfile.php";
   include_once($path);
?>

If your server doesn't populate the "document_root", you may need this



    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");
raphvon

You can add an include_path = ".:/home/myuser/mysite.com/" to your php.ini or you can add something like this into your script before the include or require:

set_include_path(get_include_path() . ":/home/myuser/mysite.com/");

The first one will work for all the scripts running in your website.

The second option will only work for the script which has the setincludepath on the code, for the rest of the application it will not work unless you have an object you call in every script that add the setincludepath.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!