php includes

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
jessevitrone
Forum Newbie
Posts: 15
Joined: Tue Aug 12, 2003 2:42 pm

php includes

Post by jessevitrone »

I'm having some trouble with include, and I'm not sure if there's a way around it.

Here's a simplified version of my directories and files:

test.php
actions/login.php
classes/config.php
classes/database.php

My config.php includes database.php.

When I try to have test.php include config.php, config.php can't find database.php because it's looking in the directory that test.php is in, not it's current directory.

Is there some way around this? I realize that I can just have test.php do the database.php include before I include config.php, but I was hoping to avoid doing that.

Thanks for any suggestions,
Jesse
jessevitrone
Forum Newbie
Posts: 15
Joined: Tue Aug 12, 2003 2:42 pm

Post by jessevitrone »

Is there some way to include a file with an absolute path, and not a relative path? Absolute with respect to the web app though, not to the server where I have to start it off with something like /usr

Thanks.
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post by twigletmac »

If $_SERVER['DOCUMENT_ROOT'] is set you could use that to build more absolute paths.

Mac
djot
Forum Contributor
Posts: 313
Joined: Wed Jan 14, 2004 10:21 am
Location: planet earth
Contact:

Post by djot »

-

Yes there is, you can try $ _SERVER["DOCUMENT_ROOT"],

But it has some disadvantage, because it's behaviour is different on each server. Sometimes it returns

e.g
/var/www/user/~username/
sometimes only
/~username/

,so you will run in trouble than again.

That is my experience with document_root.

Another way is to set a global variable, that holds if you include from root or from upper folder and adjust the path then with an if clause.

like

Code: Select all

<?php

// include from root (./)
if ($yourglobalvar == "root") { include_once('./classes/config.php'); }
// include from e.g. ./actions/ 
else { include_once('../classes/config.php'); }

?>
Not very nice, but that is safe on all servers.


djot
-
Last edited by djot on Tue Oct 12, 2004 8:39 am, edited 3 times in total.
jessevitrone
Forum Newbie
Posts: 15
Joined: Tue Aug 12, 2003 2:42 pm

Post by jessevitrone »

yeah, seems like there's another trick using

include(dirname(__FILE__) . '/path/relative/file_to_include.php');

to include it relative to the current file, and not to the original file.

Thanks for the suggestion.
Post Reply