需要/包含php文件时更改文件夹路径

时间:2013-10-03 14:55:12

标签: php include require include-path server-side-includes

我目前正在使用index.php来包含另一个文件,它的结构如下:

root / index.php
     / new/ index.php
          / img/ test.jpg

我在root / index.php中写了以下内容:

<?php
require_once("new/index.php");
?>

问题是,其中的所有路径都是错误的。因为所有路径都基于new / index.php。

例如,在new / index.php中,我的test.jpg就像

<img src="img/test.jpg" />

当我直接访问new / index.php

时显示http://www.test.com/new/img/test.jpg

但是当我在index.php中包含php时,它会显示http://www.test.com/img/test.jpg

如何解决?我试过chdir()但是它不起作用期待谢谢

3 个答案:

答案 0 :(得分:5)

确保始终包含绝对路径,例如:

require_once(dirname(__FILE__) . "/otherfile.php");
require_once(dirname(__FILE__) . "/../uponefolder.php");
require_once(dirname(__FILE__) . "/sub/folder/file.php");

或使用自动加载。

答案 1 :(得分:2)

你刚问过两次同样的问题吗? Use the required / included file as base directory in PHP

在那里看我的答案。

答案 2 :(得分:1)

您在require_once()函数中的文件夹路径是相对于您的页面当前所在的目录。请查看set_include_path函数。具体来说,您可以将该函数添加到脚本的顶部以设置根包含文件夹。像这样:

set_include_path("/var/www/html/root");
require_once("new/index.php");