when including() or require() do I always have to use ../../ relative to my file? Is there a simple way?

断了今生、忘了曾经 提交于 2019-12-11 12:48:12

问题


I'm building a web app that has php files spread out through different directories, so a typical file may have several includes. All these files everywhere.

a php file may look like this:

include('../../some.php');
require('../../some.php');

and in another file you may have something like this:

 include('../../../../some.php');
require('../../../../some.php');

point being, this can get a little bit out of hand, and somewhat difficult to keep track of. Is there a way I can do this so that I don't need to ../../.. all the time?

I tried doing this:

include('http://www.mywebsite.com/some.php');
require('http://www.mywebsite.com/some.php');

but it doesn't seem to work, but what's funny is that I won't get a PHP error when I use require, only a call to function x() error, function or object doesn't exist type error. It never said anything about the file not existing. Thank you in advance.


回答1:


Do not trust $_SERVER variables. In some environments they can be set/altered by the user making the request. It's much better to define the base path manually in your index/bootstrap file and use it when needed.

define('SYSTEM_PATH', __DIR__ . '/');

or on version of PHP before 5.3 you can do this

define('SYSTEM_PATH', dirname(__FILE__) . '/');

Now you can always know the path to your files.

require(SYSTEM_PATH . 'lib/class.php');

Both __DIR__ and __FILE__ are safe constants set by PHP and can be trusted.

You can autoload classes like this:

function __autoload($class_name)
{
    require SYSTEM_PATH . strtolower($class_name) . '.php';
}

In other news, I can't ever think of a good use for include(). If you need to use include you are doing something wrong.




回答2:


this is what include paths were invented for. if there is a folder outside of your public folder that you use often, make an include path leading to it. this way you can treat it as if it were in the same folder as everything else.

http://php.net/manual/en/function.set-include-path.php

Better than that however, create a class autoloader...

http://php.net/manual/en/language.oop5.autoload.php




回答3:


Use this:

include($_SERVER['DOCUMENT_ROOT'] . '/inc/connect.php');

This will bring you to the document root, then build the rest from there...




回答4:


You can set the include path in php.ini, or you can change the working directory with chdir. I prefer both, to be on the safe side, but this works just fine:

chdir($_SERVER['DOCUMENT_ROOT']);

Now you can include your files as if the current one were in the root folder.



来源:https://stackoverflow.com/questions/10307426/when-including-or-require-do-i-always-have-to-use-relative-to-my-file

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