Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for PHP paths [duplicate]

Tags:

path

php

twig

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.

like image 752
Nath5 Avatar asked May 03 '12 04:05

Nath5


1 Answers

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(); 
?>
like image 146
Lawrence Cherone Avatar answered Oct 09 '22 20:10

Lawrence Cherone