PHP - Absolute path to folders when creating a new subfolder

376 views Asked by At

I don't have much skills on PHP, but how do I define a root path on all files inside subfolders? Let's take an example: Images, css and other shared folders are on the site's root. If I create a subfolder called 'myfolder' and insert a php file that's quite similar to the root's main index.php, how do I prevent from updating all the relative paths with '../' one by one?

I guess this might be quite easy to solve, but I'm quite a newbie on this.

Thanks in advance

2

There are 2 answers

0
Oleg On

You can use <?php echo $_SERVER['DOCUMENT_ROOT'] . '/yourfolder/style.css'; ?>

Or you can define variable like $basePath and set it to http://yoursite.com/ and use this var in every place where you print images, styles, etc <?php echo $basePath . '/yourfolder/style.css'; ?>

1
Kevin_Kinsey On

The magic constants

__FILE__

and

__DIR__ 

will probably be of help to you. For example, to get the path to the file that needs to know where it's located:

$where_am_i = realpath (__DIR__);

So, "images" relative to the calling file would be $where_am_i/images, etc.