使 php 包含子目录中的工作
好的,我正在为我的自定义博客创建一个管理界面,网址为 /admin。
我是否可以使用相同的包含(包括自动加载)作为根目录。
如果可能的话,我还希望能够自动更正导航中的链接,以便在从 /admin 访问时将 / 中的 index.php 更改为 ../index.php。
谢谢,尼科
Ok, I am creating an admin interface for my custom blog at the url /admin.
Is it possible for me to be able to use the same includes (including autoload), as the root directory.
If possible, I would also like to be able to automatically correct the links in the navigation so that they go that index.php in / changes to ../index.php when accessed from /admin.
Thanks, Nico
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
最佳实践是定义一个“ABSOLUTE_PATH”常量,其中包含所有内容所在的目录。 之后,您可以简单地复制并粘贴所有内容,因为它定义了“完整”路径,该路径不会因目录而异。
示例
然后在任何时候您都可以简单地执行此操作来包含文件
The best practice for this is to define a 'ABSOLUTE_PATH' constant that contains the directory that everything is located under. After that, you can simply copy and paste everything, because it is defining the 'full' path, which doesn't change from directory to directory.
Example
Then at any point you can simply do this to include a file
最简单的方法是使用绝对路径/URL。
对于 URL,在某处定义一个常量/变量,指向应用程序的根目录,例如 :
或
在每个链接中使用它,例如 :
这样,总是可以的(以及在另一台服务器上安装项目的那天,或者在子目录中,您只有一个常量/变量需要修改,并且一切仍然有效)
对于包含/需要,也始终使用绝对路径; 一种解决方案是使用
dirname
,如下所示:__FILE__
是当前文件,您正在其中写入此行;dirname
获取包含该文件的目录的路径(完整路径)。这样,您就不必担心文件的相对路径。
Easiest way would be to use absolute pathes / URLs.
For the URLs, define a constant/variable somewhere, that points to the root of your application, like :
or
And use it in every link, like :
This way, always OK (and the day you install your project on another server, or in a subdirectory, you only have one constant/variable to modify, and everything still works)
For includes / requires, always use absolute pathes too ; one solution is to use
dirname
, like this :__FILE__
is the current file, where you are writing this line ;dirname
gets the path (the full path) to the directory containing that file.With that, you never have to worry about the relative paths of your files.
还有一个答案类似于结合前两个建议。 您可以定义常量:
然后,假设 config.php 需要包含在站点的许多文件中,那么您可以使用以下语句来完成此操作:
希望这会有所帮助。
Yet another answer would be similar to combining the first two suggestions. You could define the constant:
Then, assuming that
config.php
needs to be included in many files of the site then you can use the following statement to accomplish this:Hope this helps.
我过去用于functions.php 的另一个选项是类自动加载器。
这在某些情况下有效,并且在过去当我不想定义绝对 $root url 时对我很有帮助。
Another option that I've used for functions.php in the past is a class autoloader.
This works under certain circumstances and has been helpful to me in the past when I don't want to define an absolute $root url.