php - 头文件 - 相对路径问题
我有一个 php 网络应用程序。我有一个 header.php
文件,其中包含开始 html 标签、元数据、css、js 文件。
我在此应用程序中有多个文件夹。我已经在 header.php
中给出了 css、js 文件的相对路径。我面临的问题是,当我将此 header.php
文件包含在其他文件(例如 ./test-folder/my-file.php
)中时,相对路径休息。
所以为了解决这个问题,我在需要的地方给出了绝对路径。但每次上传到服务器时我都必须更改这些路径。可以通过其他方式完成此操作吗?
预先感谢
安吉
I have a web application in php. I have a header.php
file where I have the opening html tag, meta data, css,js file includes.
I have multiple folders in this application. I have given relative paths to the css,js files in the header.php
. The problem I am facing is, when I include this header.php
file in some other file say, ./test-folder/my-file.php
, the relative paths break.
so to solve this i have given absolute paths where ever needed. But I have to change these paths every time I upload on to server. Can this be done in any other way?
Thanks in advance
Anji
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不要对路径使用静态值,而是为文档根定义一个常量并使用该常量,
在包含文件时,您可以使用此常量。
Do not use static value for path instead define a constant for document root and use that constant
While including files you can use this constant.
您的应用程序中的架构很糟糕。尝试搜索有关 MVC 的信息。< br>
这个答案可能有用:https://stackoverflow.com/questions/5721353/what-is-良好的编程架构/5793753#5793753
因此:
You have bad architecture in your application. Try to search info about MVC.
This answer may be useful: https://stackoverflow.com/questions/5721353/what-is-good-neat-architecture-in-programming/5793753#5793753
So:
相对路径是相对于当前工作目录(cwd)的。如果您只是包含另一个文件,则 cwd 不会更改。
如果您想要具有(某种程度上)相对于当前脚本文件路径的路径,您可以使用例如
或从 php 5.3 开始,
另请参阅:
Relative paths are relative to the current working directory (cwd). If you just include another file that cwd does not change.
If you want to have paths that are (somewhat) relative to the current script file path you can use e.g.
or as of php 5.3
see also: http://docs.php.net/language.constants.predefined
如果我正确理解您的问题,您只想知道应用程序的根文件夹,而不需要对其进行硬编码。
更简单的方法是定义一个常量,正如 Shakti 所回答的那样。
但是,您实际上可以在根文件夹中拥有一个具有唯一名称的文件,例如“foobar”,然后从当前目录沿着树向上查找,直到找到 foobar。
If I understood your question right, you just would like to know the root folder your application without the need to hardcode it.
The easier way is to define a constant as Shakti has answered.
However, you could actually have a file with a unique name such as "foobar" in the root folder, then walk up the tree from current directory until you find foobar.