PHP:include file
I have a DB file content my DB info. the file db.php located on my mother's folder [here apps folder]. Now, how can I include the db.php file anywhere on the project using base_url()
? Here is my base url function:
function base_url() {
return "http://localhost/apps";
}
I tried like this way but it does not wo开发者_运维知识库rk.
$link=base_url()."/"."db.php";
include('$link');
Can anybody please help>
Thanks riad
base_url()
needs to return a file path here, not a http://
URL.
(It would then probably make sense to rename it to base_path()
)
multiple problems.
include('$link');
will never ever work because the single quotes mean the literal string $link and not the value of the variable, you'll be needing to useinclude($link)
orinclude("$link");
- include is a language construct not a function, so you only need
include $link;
- stipulating "/" as the directory separator could cause problems, PHP provides a constant for you to use
DIRECTORY_SEPARATOR
- your base_url function should return a file path not an URL
- base_url should probably just be a constant seeing as it won't change
here's a version which should work for you
function application_root()
{
return dirname(__FILE__) . DIRECTORY_SEPARATOR;
}
$link = application_root() . 'db.php';
include $link;
include('../db.php');
"../" will reapeat (eg '../../../db.php') as depth of the file from which you are including
you can use $_SERVER['DOCUMENT_ROOT'] var as the base URL/PATH too
Within single quotes variable occurrences like your $link
are not substituted by their values. But you can simply write this:
$link = base_url()."/db.php";
include $link;
Now if this works as expected depends on whether you want the source code of db.php to be included or just the output of db.php. Because working on the filesystem gets you the source code while requesting it via HTTP gets you the output.
精彩评论