如何在PHP中设置绝对包含路径? [英] How do I set an absolute include path in PHP?
问题描述
在HTML中,我可以找到文件,该文件从 Web服务器的根文件夹开始,方法是以"/"开头.喜欢:
In HTML, I can find a file starting from the web server's root folder by beginning the filepath with "/". Like:
/images/some_image.jpg
我可以将该路径放在任何子目录中的任何文件中,它将指向正确的图像.
I can put that path in any file in any subdirectory, and it will point to the right image.
使用PHP,我尝试了类似的操作:
With PHP, I tried something similar:
include("/includes/header.php");
...但这不起作用.
...but that doesn't work.
我认为此页面就是说我可以设置一次include_path
,然后再设置一次.但是我不太了解语法.这两个示例都以句点开头,并显示:
I think that that this page is saying that I can set include_path
once and after that, it will be assumed. But I don't quite get the syntax. Both examples start with a period, and it says:
使用.包含路径中的允许相对包含,因为这意味着当前目录.
Using a . in the include path allows for relative includes as it means the current directory.
相对包含正是我不想要想要的.
Relative includes are exactly what I don't want.
如何确保所有包含的内容都指向root/includes
文件夹?(奖金:如果我要将该文件夹放置在公共目录之外怎么办?)
How do I make sure that all my includes point to the root/includes
folder? (Bonus: what if I want to place that folder outside the public directory?)
我的开发文件当前由XAMPP/Apache提供.这会影响绝对路径吗? (我不确定生产服务器将是什么.)
My development files are currently being served by XAMPP/Apache. Does that affect the absolute path? (I'm not sure yet what the production server will be.)
我不知道我的问题在这里.我在上面引用的include_path
正是我在寻找的东西,其语法并没有真正使人迷惑.我刚刚尝试过,效果很好.
I don't know what my problem was here. The include_path
thing I referenced above was exactly what I was looking for, and the syntax isn't really confusing. I just tried it and it works great.
我想到的一件事是,有些人可能认为"/some/path"是绝对路径",因为他们认为操作系统是Linux.该服务器是Windows,因此绝对路径必须以驱动器名称开头.
One thing that occurs to me is that some people may have thought that "/some/path" was an "absolute path" because they assumed the OS was Linux. This server is Windows, so an absolute path would have to start with the drive name.
无论如何,问题已解决! :)
Anyway, problem solved! :)
推荐答案
我要做的是将config.php文件放在我的根目录中.该文件包含在我的项目中的所有PHP文件中.在该config.php文件中,然后执行以下操作;
What I do is put a config.php file in my root directory. This file is included by all PHP files in my project. In that config.php file, I then do the following;
define( 'ROOT_DIR', dirname(__FILE__) );
然后在所有文件中,我知道项目的根目录是什么,并且可以做类似的事情
Then in all files, I know what the root of my project is and can do stuff like this
require_once( ROOT_DIR.'/include/functions.php' );
对不起,没有其他积分可以进入公共目录;)这还带来了不幸的副作用,即您仍然需要相对路径才能找到config.php,但是使其余的内容变得更加容易.
Sorry, no bonus points for getting outside of the public directory ;) This also has the unfortunate side affect that you still need a relative path for finding config.php, but it makes the rest of your includes much easier.
这篇关于如何在PHP中设置绝对包含路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!