Link to home
Start Free TrialLog in
Avatar of andycal
andycal

asked on

PHP include paths

More of a general one this. I've got a bunch of classes that I use day to day. I've been playing with one of them, and I have tried to include another file at the top of the class containing some configuration options.

My path is like this:

/root/index.php

root/includes/class.inc.php
root/includes/config.inc.php

So, the index includes the class, and the class includes the config.inc.php.

However, am I right in thinking, that for the class to include the config.inc.php, it will start the path from where *it* was originally called? i.e if my class file simply has include('config.inc.php'); it will in fact try to call it in from the root directory, not where the class itself is stored?

What's the most flexible way around this?
Avatar of gruntar
gruntar

you can include a file that is not in a root dir where index.php is like this

include("includes/config.inc.php");

Cheers
if you want to include a file once use
require_once or include_once, so such a php-file is only included once, even if its called with require_once multiple times.

I typical have a fill which includes all nexessary thing e.g

config.php
<?php

// make settings
....

//include classes and function

require_once 'includes/class.inc.php';
require_once 'includes/class2.inc.php';
....

on the pages i use the only do a
require_once 'config.php';
Avatar of andycal

ASKER

That's kinda relying on knowing always the path, I guess what I'm after is a way of ensuring that the config file is called into the class file, always using the class file path.
you can also set your include_path directive in the php ini file such so that PHP searches for included files in the way that you want. You can do this in your script at runtime using ini_set():
http://us2.php.net/manual/en/function.ini-set.php

For information on include_path:
http://us2.php.net/manual/en/ini.sect.path-directory.php#ini.include-path

From the PHP manual:
Files for including are first looked in include_path relative to the current working directory and then in include_path relative to the directory of current script. E.g. if your include_path is ., current working directory is /www/, you included include/a.php and there is include "b.php" in that file, b.php is first looked in /www/ and then in /www/include/.

Cheers,
Matt
To this you just have to set up include path, where your includes reside like this
include_path=".:/root/includes"

then you include those files just like if they were in root
include('config.inc.php');
That way your include will be the same no matter in what direcory file is.

Cheers
ASKER CERTIFIED SOLUTION
Avatar of Roonaan
Roonaan
Flag of Netherlands image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial