Dan
Dan

Reputation: 299

PHP require_once two files with the same name

This is a weird situation... I'm trying to create an extension for a PHP program "A" which integrates with another program "B".

Here's the problem, both "A" and "B" have files named "config.php", containing their configuration. So what happens is that script A has:

requice_once("config.php");
...
require_once("../B/something.php");

Then "something.php" also has

require_once("config.php");

Which is a different file because it's in a different directory - But PHP doesn't notice that and the second file is not included.

I managed to find a really ugly solution of renaming the second "config.php" as well as all references to it but this will obviously make maintenance a pain... is there a better way?

EDIT -

OK, Maybe I oversimplified a little bit. "A" is actually "phpBB", for which I'm writing an extension (and I don't want to start modifying the main program because it'll make maintenance unbearable), so I can't make any changes to the code that includes the first instance of config. I implement an API by extending a given base class, then phpBB calls my class' __construct method with one of the arguments being $phpbb_root_path, which is the directory where phpBB is installed. Then from the extension I do this:

require_once($phpbb_root_path . "../B/something.php");

"B" is an in-house developed package (not yet open-source so I can't give exact file names), that why it was easier for me to rename "config.php" to "configuration.php" for an ugly fix. Everything there is in a single directory. The exact tree is

htdocs
  | - phpbb
  |     |
  |     | - config.php
  |     | - ext/{long path}/myextension.php
  |
  | --- B
  |     | - config.php
  |     | - something.php

Thanks, sorry for the big explantion.

Upvotes: 2

Views: 956

Answers (1)

Martin
Martin

Reputation: 22760

Assuming your htdocs directory is your PHP $_SERVER['DOCUMENT_ROOT'] location, then you can simply include the files using better specificity.

You need to specify not only which file you want, but where exactly the file is located.

so; from your edit showing your file tree:

requice_once $_SERVER['DOCUMENT_ROOT']."/phpbb/config.php";
...
require_once $_SERVER['DOCUMENT_ROOT']."/B/something.php";

Then "something.php" also has

require_once $_SERVER['DOCUMENT_ROOT']."/B/config.php";

NOTES

  • You should not wrap include or require values in brackets.
  • You should not use relative pathing (.., etc.), always give an absolute filepath.
  • Generally, try and avoid using _once functions they are heavy lifters, and expensive with memory and you probably don't need them (especially if you're absolutely pathing)
  • Even if $_SERVER['DOCUMENT_ROOT'] is not the exact solution for your situation, you can take the concept given here and apply it accordingly.

Upvotes: 1

Related Questions