문제

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

도움이 되었습니까?

해결책

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.

다른 팁

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

See my answer there.

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");

You could simply change the included HTML document base by adding a base tag. https://developer.mozilla.org/fr/docs/Web/HTML/Element/base

<head>
  <base href="your_new_url_base" target="_blank">
</head>

The HTML included file could check "Am I included from a parent?" if so "I have to change my base tag"...

// new/index.php

echo '<head>';

if (basename(__FILE__) == basename($_SERVER["SCRIPT_FILENAME"])) {
  // called directly, no need base tag;
} else {
  // included/required
  echo '<base href="your_new_url_base" target="_blank">';
}

echo '</head>';
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top