Change of folder path when require/ include an php file

你说的曾经没有我的故事 提交于 2019-12-13 04:45:36

问题


I am currently using an index.php to include another file , it structure like:

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

And I write following in root/index.php :

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

the problem is , all paths in it are wrong. As all paths are based on new/index.php.

For example, In new/index.php my test.jpg is like

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

It shows http://www.test.com/new/img/test.jpg when I directly access new/index.php

But it shows http://www.test.com/img/test.jpg when I include the php in index.php.

How to fix it? I tried chdir() but it does not work expect Thanks


回答1:


Make sure you always include with an absolute path, like:

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

Or use autoloading.




回答2:


Did you just ask the same question twice? Use the required / included file as base directory in PHP

See my answer there.




回答3:


The folder path you have in the require_once() function is relative to the directory your page is currently in. Have a look at the set_include_path function. Specifically, you could add that function to the top of your scripts to set the root include folder. Something like this:

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


来源:https://stackoverflow.com/questions/19162434/change-of-folder-path-when-require-include-an-php-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!