...

View Full Version : include(); from DOCUMENT_ROOT not working inside of a function



DR.Wong
01-25-2012, 08:47 AM
Hi all!

I am having a problem including a file inside of a function.

This works :



function queryDB($query)
{
include '../includes/config.php';
}


And this does not :



$configFileLocation=$_SERVER['DOCUMENT_ROOT']."/includes/config.php";
function queryDB($query)
{
include $configFileLocation;
}


Neither does this :



function queryDB($query)
{
include $_SERVER['DOCUMENT_ROOT']."/includes/config.php";
}


If the config file is included using the $configFileLocation variable outside of the function, the variables in the config.php file are available. When included inside of the function (using via $configFileLocation), they are not.

What am I missing?

Thanks a lot.

abduraooft
01-25-2012, 09:09 AM
Do you get your actual document root for
echo $_SERVER['DOCUMENT_ROOT'];
Check the output of the above and then find out whether
$_SERVER['DOCUMENT_ROOT']."/includes/config.php"; becomes the actual path to that file.


And this does not :


$configFileLocation=$_SERVER['DOCUMENT_ROOT']."/includes/config.php";
function queryDB($query)
{
include $configFileLocation;
}
In the above code, the variable $configFileLocation won't get scope inside that function, unless you declare it as a global variable .

DR.Wong
01-25-2012, 09:18 AM
Yes, the $_SERVER['DOCUMENT_ROOT'] value is correct.

Here is a better explanation :

config.php


//DATABASE CONFIGURATION
$dbUsername="FOO";
$dbPassword="BAR";
$dbIP="localhost";
$database="myDataBase";


test.php


$configFileLocation=$_SERVER['DOCUMENT_ROOT'].'includes/config.php';
include $configFileLocation;

echo $dbUsername;

//This works, echos FOO

function myFunction()
{
include $configFileLocation;

echo $dbUserName;

}

myFunction();

//This does not work, echos nothing and the function which actually uses the db info returns an error "no database selected".

DR.Wong
01-25-2012, 09:32 AM
Sill mistake.

I was declaring $configFileLocation outside of the function and then trying to use it inside of the function.

Solved.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum