Eli Eli - 3 months ago 16
PHP Question

how to include a file in php and still respect the relative links from that included file

I am experimenting in PHP and was wondering how I could do something like this

if (site is wordpress)
include wordpress index.php;


in the wordpress file there is a line

require('./wp-blog-header.php');


that wont work because it throws me file not found error, it will work however if i change it to this

require('wp-blog-header.php');


then i don't get a problem and the page loads (well to some extend because the wp-blog-header.php loads in some other files that are relative to wp-blog-header.php so those don't get included or loaded).

Is there some way to trick PHP into keeping and respect the relative files?

EDIT: Included my code for better context of my question

if ($app['framework']['type'] && $app['cms']['type']) {
echo "Only a Framework or CMS can be loaded at a time...";
} else {
if (is_file("./app/" . $cfg['application']['name'] . "/index.php")) {
require_once "./app/" . $cfg['application']['name'] . "/index.php";
} else {
if ($app['framework']['type']) {
echo "framework";
//require_once "./app/" . $cfg['application']['name'] . "/" . $app['framework']['type'] . "/index.php";
} else if ($app['cms']['type']) {
if ($admin) {
require_once "./app/" . $cfg['application']['name'] . "/" . $app['cms']['type'] . "/wp-admin/index.php";
} else {
$old_working_dir = getcwd(); // Remember where we are now.
chdir("./app/" . $cfg['application']['name'] . "/" . $app['cms']['type'] . "/"); // 'Go into' the Wordpress directory.
//include("index.php"); // Include the index.php file (no need for 'wordpress/')
chdir($old_working_dir);
require_once "index.php";
}
} else {
echo "There is no index in your project directory, if your going to use a Framework or CMS please choose one from the following, thank you (list of cms's and frameworks)";
}
}
exit;
}

Answer

You can use the function getcwd() to get the current working directory and chdir() to set it. In your case, it'd look something like this:

$old_working_dir = getcwd();   // Remember where we are now.
chdir("wordpress");            // 'Go into' the Wordpress directory.
include("index.php");          // Include the index.php file (no need for 'wordpress/')
chdir($old_working_dir);       // Go back to the previous directory.

Or:

chdir("wordpress");
include("index.php");
chdir("../");                  // Go back up one level.