0

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

4 Answers 4

6

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.

Sign up to request clarification or add additional context in comments.

8 Comments

thanks for your help , when I open the index.php the image file is still broken
How are you generating the path?
Turn it into an absolute (web)path.
but when I include new/index.php in index.php , it will be img/test.jpg instead of new/img/test.jpg
|
2

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

See my answer there.

Comments

1

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

Comments

0

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>';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.