relative path confusion

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
phpBever
Forum Commoner
Posts: 42
Joined: Fri Aug 07, 2009 10:23 am

relative path confusion

Post by phpBever »

I'm wondering if I'm not understanding relative path correctly.

I've got a php file in http://www.site/ws (that is, /ws/file.php). I want to include a file at http://www.site/otherdirectory/toBeIncluded.php. I would think that this would work:

include("../otherdirectory/toBeIncluded.php");

But for some reason it chokes on that. If I enter the absolute path (http://www.site/otherdirectory/toBeIncluded.php) it works and if I create a shortcut in /ws it works.

Is there some reason I'm missing that include("../otherdirectory/toBeIncluded") doesn't work?

Thanks
mikosiko
Forum Regular
Posts: 757
Joined: Wed Jan 13, 2010 7:22 pm

Re: relative path confusion

Post by mikosiko »

all depend of the relative location of your folder "otherdirectory" ...

did you try
include("/otherdirectory/toBeIncluded.php"); ?
phpBever
Forum Commoner
Posts: 42
Joined: Fri Aug 07, 2009 10:23 am

Re: relative path confusion

Post by phpBever »

I have concluded that the problem has something to do with where I place stuff in a webservice I'm trying to build using the WSDL_gen.php program rather than with some mistake in my relative address.

Thanks.
cpetercarter
Forum Contributor
Posts: 474
Joined: Sat Jul 25, 2009 2:00 am

Re: relative path confusion

Post by cpetercarter »

It is in general a not good idea to use relative paths in 'include' statements. It makes your code less portable. For example, if you decide to move file.php, you would need to hunt through it for every relative 'include', and change the path. It is better to define a constant to represent the absolute path from your server root to the directory where your include files are :

Code: Select all

define (INCLUDE_FILES, "/path/from/root/to/include/directory/");
and then

Code: Select all

include INCLUDE_FILES . "toBeIncluded.php";
phpBever
Forum Commoner
Posts: 42
Joined: Fri Aug 07, 2009 10:23 am

Re: relative path confusion

Post by phpBever »

Good point. Thanks.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: relative path confusion

Post by requinix »

+1 to not being portable.

The other common solution is to use the DOCUMENT_ROOT.

Code: Select all

include $_SERVER["DOCUMENT_ROOT"] . "/otherdirectory/toBeIncluded.php";
Post Reply