php包含根目录以外的目录中的文件

JTJ*_*TJM 2 php include

我有一个全局模板页面,/layout_header.php以及存储的其他一些文件/aFolder/index.php.

/layout_header.php,我有:

<?php
    // Reference to scripts and other files
    echo "<img src='img/lollipop.png'/>";
    echo "<script src='js/move.js'/>";
    echo "<a href='aFolder/movement.php'>Click here!</a>";
?>
Run Code Online (Sandbox Code Playgroud)

/aFolder/index.php,我有:

<?php
    include "../layout_header.php";
?>
Run Code Online (Sandbox Code Playgroud)

现在,/aFolder/index.php调用该/layout_header.php文件没有问题.不幸的是,因为目录现在/aFolder,我面临以下问题:

  • 无法查看图像,因为图像现在链接为/aFolder/img/lollipop.png(不存在)
  • 由于上面列出的原因,无法执行脚本.
  • 由于上面列出的原因,网址无效.

我的许多脚本和css文件都使用相对路径.换句话说,如果index.php放在根文件夹中,一切正常.

我该如何解决子目录中的文件问题?

K-G*_*Gun 7

您可以在所有PHP框架(至少是专业人员)中看到变量/常量为APPPATH,BASEPATH等.因此,您需要在项目中定义类似的变量/常量并根据需要使用它.

<?php
// a.php: assuming this included everywhere at very first line 
// and located in root directory
// preferable, define a constant instead of variable, cos it 
// may used in functions directly without "global $ROOT";

// for "include"
define('ROOT', __DIR__); // for PHP >= 5.3
define('ROOT', realpath(dirname(__FILE__)));  // for PHP < 5.3
// for "src, href" etc
define('HTTP', $_SERVER['SERVER_NAME']); // for local development support i.e foo.com.local

// includes
include ROOT .'/layout_header.php';
include ROOT .'/classes/mailer.php';
include ROOT .'/foo/bar/baz.php';
...

// src,href
printf('<script src="%s/js/move.js" />', HTTP);
printf('<img src="%s/img/lollipop.png" />', HTTP);

print '<a href="'. HTTP .'/aFolder/movement.php">Click here!</a>';
...
?>
Run Code Online (Sandbox Code Playgroud)


Ank*_*nha 5

总是使用$ _SERVER ['DOCUMENT_ROOT'].'path/to/file'来包含php文件的相对位置.

对于图像和脚本文件以及css文件,请使用yourdomain.com/path/to/file.extension