Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Includes Confusion

Tags:

include

php

I'm building the basic framework for my website and I have a config.php file stored in a scr directory. Additionally, this directory has a folder called php where I store a file called sidebar.php

Basically, the config.php file will hold my database configuration variables and is also the only file called by every page. I wish to include php/sidebar.php in this file so any variables I create in sidebar.php can be used on all pages.

However, I also want sidebar.php to have access to the database configuration variables. So these two files will effectively be including each other.

The include from config to sidebar is:

include 'php/sidebar.php';

From sidebar to config is:

include '../config.php';

However, the above statement (sidebar to config) yields the below error message:

Warning: include(../config.php) [function.include]: failed to open stream:

No such file or directory in C:\xampp\website\scr\php\sidebar.php on line 3

Am I going about this all wrong cross-linking the two files or is there a decent reason why it's not working

like image 657
Dan Hanly Avatar asked Dec 21 '22 16:12

Dan Hanly


2 Answers

Generally speaking, a secure way of doing includes is to use dirname(__FILE__), or __DIR__ if you're using PHP >= 5.3, to have an absolute path -- written relatively from the current one.

For instance, you could use :

include dirname(__FILE__) . '/php/sidebar.php';


Note : dirname(__FILE__) and __DIR__ point to the directory of the file in which they are written.

With that, no need to worry what is included from where and includes what : you always reference files using absolute pahts.


Relevant pages in the manual :

  • dirname()
  • Magic constants ; amongst which you'll find __FILE__ and __DIR__.


Also, as @jwir3 pointed out in his comment, you'll sometimes want to use require_once() or include_once(), to make sure a given file is not included more than once.

Including a file more than once can lead to trouble, especially if it contains constants, functions, or classes definitons.

like image 100
Pascal MARTIN Avatar answered Dec 28 '22 21:12

Pascal MARTIN


I guess that the php parser is already reading the file. You should use include_once instead of include to avoid this problem.

Aditionally you should also strongly consider require_once as it protect against the case where the included file doesn't exists, especially for a configuration file, your app should crash instead of ignoring it (And that's what require does).

PS : As other said the cyclic dependency should be broken anyway it's a pretty good sign of bad design.

like image 39
Julien Roncaglia Avatar answered Dec 28 '22 22:12

Julien Roncaglia