Jump to content

why do includes work different in php?


delphi123

Recommended Posts

Ok I've never had this problem using ASP at work, but it's bugging me silly now I'm using php.

 

Lets say there are 3 files

./main.php

./include/1.php

./include/2.php

 

if 1.php is included by main.php and 1.php then includes 2.php you would expect to be able to say:

 

//in main.php

include "./include/1.php";

 

//in 1.php

include "2.php";

 

However this doesn't work and it seems to need to intepret the directory location directly from the highest level include.

 

Is there any way to get php to work like asp does?  This is very counter intuitive and defeats most of the point of includes - this has meant I have to code everything with absolute links everywhere.

 

I'm hoping I've just missed an option somewhere though!

Link to comment
https://forums.phpfreaks.com/topic/83599-why-do-includes-work-different-in-php/
Share on other sites

hi revraz,  yeah that works fine - but it seems to be when I have includes WITHIN includes that the trouble starts.

 

So in ASP I'd say:

 

/www/index.php < this file includes the file header.php with the path includes/header/header.php

 

/www/includes/header/header.php < this file includes the file logo.php with the path images/logo.php

 

/www/includes/header/images/logo.php

 

But in php it doesn't appear to work like that and header.php would need a path of includes/header/images/logo.php to include logo.php if I wanted it to work in index.php (or an absolute path)

In php the path in which everything gets included from is from the parent include (in your case www/index.php). PHP does not include files in which the included file is located to.

 

What I'd do is setup a constant call this contant SITEROOT and set that constant to your websites root folder, eg:

define('SITEROOT', $_SERVER['DOCUMENT_ROOT']);

 

Now whenever you go to include a file do:

include(SITEROOT . '/path/to/file');

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.