本文介绍了当include()或require()我总是要使用../../相对于我的文件?有没有一个简单的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个网页应用程序,它通过不同的目录传播php文件,所以典型的文件可能包含几个。所有这些文件无处不在。



一个php文件可能如下所示:

 包括( '../../ some.php'); 
require('../../ some.php');

在另一个文件中,您可能会有这样的情况:

  include('../../../../ some.php'); 
require('../../../../ some.php');点这个,这可以得到一点点失控,有些难以跟踪。有没有办法,我可以这样做,所以我不需要 ../../ .. 所有的时间?



我尝试这样做:

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

但它似乎不起作用,但有趣的是我不会得到一个PHP错误当我使用require,只有一个
调用函数x()错误,函数或对象不存在类型错误。它从来没有说过关于该文件不存在的任何内容。先谢谢你。

解决方案

不要信任 $ _ SERVER 在某些环境中,可以由发出请求的用户进行设置/更改。在索引/引导文件中手动定义基本路径是更好的,并在需要时使用它。

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

或5.3之前的PHP版本可以这样做

  define('SYSTEM_PATH',dirname(__ FILE__)。'/'); 

现在您可以随时了解文件的路径。

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

__ DIR __ __ FILE __ 是由PHP设置的安全常量,可以被信任。



您可以自动加载类,如下所示: / p>

  function __autoload($ class_name)
{
require SYSTEM_PATH。 strtolower($ class_name)。 .PHP;
}

在其他消息中,我无​​法想到一个好的用于 include()。如果你需要使用包含你做错了什么。


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 acall 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.

解决方案

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.

这篇关于当include()或require()我总是要使用../../相对于我的文件?有没有一个简单的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 05:31