Hello. When i use php include to include a page in my website all the paths in the file i include get messed up. The included page acts like it is in the same folder as the page im including from.
Is there way to avoid/fix this problem?
Hello. When i use php include to include a page in my website all the paths in the file i include get messed up. The included page acts like it is in the same folder as the page im including from.
Is there way to avoid/fix this problem?
You might need to set the include path correctly, for example via:
set_include_path(get_include_path() . PATH_SEPARATOR . 'YourPath');
Then you just need to include as if it were is the same directory:
include 'FileName.php';
No, that is the default behaviour of the php include function: It basically copies the contents of the included file into the including file. That way the instructions in the included file behave as if they were in the including file (because they are in a way).
You either have to refactor the instructions in you included file so they can operate from the folder of the including file, or add the folder of the included file to the include path.
You could use absolute paths? 'http://www.site.com/the/full/url/image.jpg'
Or even
$path = 'http://www.site.com';
and $path.'images/image.jpg'
or whatever it is
What is your include path set to? If included.php is not the same directory as page.html, you can append to you existing include path.
<?php
$path = '/path/to/includes';
set_include_path(get_include_path() . PATH_SEPARATOR . $path);
?>
Try the PHP manual
One way I try to get around this problem is by always including from where the file that is including the other file is based:
$here = dirname(__FILE__);
include($here."/../include.php");
// will include a file *allways* one level up from where *this* file is located
// and not the file that started the execution of the script.
I sometimes have files that are accessed from several different places and so the includes file path can become a bit hard to manage. So I usually try to include a configuration file at a known point then define paths to common include points.
// from a common config file
define("PATH_TO_CLASS", dirname(__FILE__)."/../class");
define("PATH_TO_MEDIA", dirname(__FILE__)."/../assets/media");
Then you can use in the file you've included the config file like:
include dirname(__FILE__)."/../config.php";
include PATH_TO_CLASS."/snassy.class.php";
Another answer for you. If things are unchangeable for some reason I've used chdir()
to some success.
For example I had mobile users come from and use a different directory than the main site, but wanted to use all of the functions and classes of the main site, so I would chdir(/to/the/main/site/folder);
right before calling the common code, which required different include paths. I would use sparingly though... as things can get confusing.