包括来自不同文件夹PHP的文件


Include files from different folder PHP

我知道这个问题已经被问了很多次,但我找不到任何合适的答案来解决我的问题。

我的文件夹结构是:

 ├── index.php
 ├── js/
 │   └── js.js
 ├── css/
 │   └── style.css
 ├── src/
 │   └── include.php
 └── level1/
     └── index.php

在include.php中:

<script src="js/jquery-1.11.0.min.js"></script>
<link href="css/style.css" type="text/css" rel="stylesheet" />

在index.php中:

<?php include('src/include.php');?> // works fine

level1/index.php中,我调用了

<?php include('../src/include.php');?> // js and css file included but points to level1 folder.

我想保留js&js&css文件夹,并且仍然能够从不同的文件夹中包括它们。

1.您必须了解php和css之间"/"的区别。对于php,它从系统的文件系统开始,但对于css/html/js,它意味着你的webroot。

2.我使用这样的代码在include.php 上

define("TEMPLATE_PATH",dirname(__FILE__)."/template");//this is for PHP file's include
include TEMPLATE_PATHE."/test.php";//php file as an example
define("WEB_TEMPLATE_PATH","/rain/template");//this is for html
<script src="<?=WEB_TEMPLATE_PATH?>/js/jquery-1.11.0.min.js"></script>
<link href="<?=WEB_TEMPLATE_PATH?>/css/style.css" type="text/css" rel="stylesheet" />

您的问题是,<script><link>将使用相对于它们所在位置的目录,即

js/jquery-1.11.0.min.js

在一种情况下,以及

level1/js/jquery-1.11.0.min.js

为了解决这个问题,如果您的目录结构在根目录上,您可以预写一个/(如注释中提到的@roullie),也可以预写像/se/appname/这样的完整路径。

您还可以提供一些返回(绝对)基本路径的全局实例,以防止键入错误和类似错误。举个例子,看看这里的代码点火器base_url()

On include.php ,filepath will different for both locations
on index.php
<script src="js/jquery-1.11.0.min.js"></script>
<link href="css/style.css" type="text/css" rel="stylesheet" />
because these file are including from index.php that is on root folder
On level1/index.php, I called
<script src="../js/jquery-1.11.0.min.js"></script>
<link href="../css/style.css" type="text/css" rel="stylesheet" />
because these file are including from level1/index.php that is in level1 folder