Tym
Tym

Reputation: 113

Can I use "include" on a server to share libraries between applications?

I have a number of web sites which use sub domains and are all in their own directory on the web server. 99% of the files in each are the same, with a handful of files which are different and peculiar to each sub domain.

I'm familiar with the include statement, but is there a way for me to have all the "core" php files in one directory, and only the unique ones in the sub domain directory and they can then reference the core ones? This would save having to maintain several copies of the same file... not good practice!

Something like this...

+-core_file_directory -index.php
|                     -file1.php
|                     -file2.php
|
+-sub_domain_1 - subdom_scheme.css
|              - unique_file.php
|
+-sub_domain_2 - subdom_scheme.css
|              - unique_file.php
|
+-sub_domain_3 - subdom_scheme.css
               - unique_file.php

I need an index.php in each sub directory, but assume I could include the index.php in the core folder? Can I include a relative path? "..\core_file_directory\index.php"?

I'm guessing this would also be more secure, in that core files are not directly public facing...?

Upvotes: 0

Views: 87

Answers (1)

IMSoP
IMSoP

Reputation: 97848

Yes, this is possible.

Note however that relative directories are relative to "the current working directory" when the script runs, which is not always what you expect.

The best way is to specify the paths using the magic constant __DIR__ which gives the absolute path of the file where you type it. So rather than include "..\core_file_directory\index.php"; you would write include __DIR__ . "\..\core_file_directory\index.php";

The other thing that will make your life a lot easier is to use class autoloading to avoid long lists of includes at the top of each file. That will also make it much easier to move things around later (e.g. to put the shared classes into a reusable package rather than a central directory) because only the autoloader needs to know the directory layout.

Upvotes: 1

Related Questions