如何使用PHP包含多个具有相对路径的目录/子目录 [英] How to use a PHP includes across multiple directories/sub directories with relative paths

查看:90
本文介绍了如何使用PHP包含多个具有相对路径的目录/子目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试构建的cms系统中遇到了问题,我基本上有一个包含header.php和footer.php文件的文件夹。



这些包含在index.php中并且工作正常。但是当我尝试在我的管理子目录下的文件中使用相同的包含时,图像和CSS就会被破坏,显然是因为相对路径现在是错误的。



所以我的问题是,我该如何克服这一点?



在阅读了其他一些关于此处以及其他各种资源的问题后,我认为绝对路径是前进的方向,但我总是使用相对路径,所以使用配置文件指定绝对路径的各种概念让我感到困惑。



我通常设法为自己工作,但这是漫长的一天,我难倒了!

解决方案

我通常在我的应用程序根目录中有一个名为config的文件,并且在其中定义了一个基本路径和其他几个常量:

  define('APP_BASE_PATH',dirname(__ FILE__)); 
define('APP_FUNCTIONS_PATH',APP_BASE_PATH。'/ functions');

我包含我的档案,例如

  include(APP_BASE_PATH。'includes / another_file.php'); 
包含(APP_FUNCTIONS_PATH。'/function_file.php');

这样,我可以将我的应用程序放在任何目录中,再加上我可以移动文件而不用担心。

也使用完整路径使得包含更快


I'm having difficulty with paths in a cms system I'm attempting to build, I've basically got a folder with my header.php and footer.php files inside.

These are included in index.php and work fine. But then when I attempt to use the same includes in a file within my admin sub directory, the images and CSS are broken, obviously because the relative path is now wrong.

So my question is, how can I overcome this?

After reading some of the other questions on here and various other sources, I think absolute paths are the way forward, but I've always used relative paths, so the various concepts of using config files to specify an absolute path are confusing me.

I usually manage to work things out for myself, but it's been a long day and Im stumped!

解决方案

i usualy have a file called config in my application root and in it i define a constant for base path and a few others:

define('APP_BASE_PATH', dirname(__FILE__));
define('APP_FUNCTIONS_PATH', APP_BASE_PATH . '/functions');

and i include my files like

include (APP_BASE_PATH . 'includes/another_file.php');
include (APP_FUNCTIONS_PATH . '/function_file.php');

that way i can place my aplication in whatever directory, plus i can move files around without to much worries.

also using full path makes the include faster

这篇关于如何使用PHP包含多个具有相对路径的目录/子目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆