I have been all over the Internet trying to figure out the best way to handle paths in my website. Should I use relative paths, absolute paths?
I have seen dirname (FILE) mentioned several times. One problem I have with relative paths is that PHP files which are included by several other files at different directory levels cause the relative paths to break. For example if the directory structure is
Root
A
B
b
And a PHP file in b and An include another file from B then the relative paths for the code in the file in B will be different.
So in general what is the best way to handle paths to files with regards to includes and file operations within the code.
Tho there are many ways to find out the path I always find it easiest to define a constant within a file on the root of the project index.php
or a config
of sort.
then I can use SITE_ROOT
for includes/class loaders ect, and SITE_URL
for views, controllers, redirects ect.
<?php
$root=pathinfo($_SERVER['SCRIPT_FILENAME']);
define ('BASE_FOLDER', basename($root['dirname']));
define ('SITE_ROOT', realpath(dirname(__FILE__)));
define ('SITE_URL', 'http://'.$_SERVER['HTTP_HOST'].'/'.BASE_FOLDER);
?>
Basic class Autoloader
<?php
function __autoload($class_name) {
include (SITE_ROOT.'/includes/'.$class_name.'.php');
}
$obj = new MyClass1();
$obj2 = new MyClass2();
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With