开发者

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.

  1. 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 use include($link) or include("$link");
  2. include is a language construct not a function, so you only need include $link;
  3. stipulating "/" as the directory separator could cause problems, PHP provides a constant for you to use DIRECTORY_SEPARATOR
  4. your base_url function should return a file path not an URL
  5. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜