Link to home
Start Free TrialLog in
Avatar of WiseGoose
WiseGoose

asked on

Universal path to a specific file or folder in php

I need to build a site on my server, and then changing to my client server with no need to change the paths, just to move the files.
Ex.: I have the config file in one folder, and the path for this template should work no matter the server is. Or I have the images folder for the galery on the root, and I neeed acess this folder from several pages, no matter where the site it is located.
Avatar of basic612
basic612
Flag of Australia image

For this you want to set up some variables in your script. By using the values of __FILE__ and      DIRECTORY_SEPARATOR constants, you should be able to include or require any files your applicaiton needs without knowing an absolute path.
To clarify, as an example you could do something like this in your script:

<?php
 
 
$application_root_directory = __FILE__;
$includes_directory = $application_root_directory .  DIRECTORY_SEPARATOR . 'includes' .  DIRECTORY_SEPARATOR;
 
require($includes_directory . 'include_me.php');
 
?>

Open in new window

Avatar of WiseGoose
WiseGoose

ASKER

Hi basic612,

Thanks. Suppose that I have a file called configure.php and I need to load it for all my scripts. This file is at the "includes" folder, wich is at a root level. I need to put the file at the top of all my scripts, and then change the server, without modify the script.
How do you adapt your script?

WiseGoose
You could also use the super global $_SERVER['DOCUMENT_ROOT']
If all of your scripts are at the root level of your application apart from the configuration file which is in includes, you can just use relative paths:

include ('includes/configuration.php');

or for better portability:

include ('includes' . DIRECTORY_SEPARATOR . 'configuration.php');

I just find it simpler typing

$includes

instead of

'includes' . DIRECTORY_SEPARATOR

each time I want to call an include file.

I personally would avoid using the $_SERVER['DOCUMENT_ROOT'] global in case your application gets installed in a subfolder of the document root. You can;t control where the folder is placed and the scripts called from, however you can expect the relative structure of your directories and files to remain constant.
Works fine your idea.
One last thing: there is a special reason for use a constant to the DIRECTORY_SEPARATOR?
Thanks.
ASKER CERTIFIED SOLUTION
Avatar of basic612
basic612
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial