Hi there, I'm trying to get the root directory of my site... But I don't want to edit the dots with slashes every time I make a new page in a directory inside another directory.. Any ideas? Here's an example tree :-)

-/
-/stuff
--/stuff/lol.php
-/lolwut
--/lolwut/cake.php
--/lolwut/pie.php

Dani AI

Generated

A couple of practical points that build on the thread: the term "root" can mean two different things — a filesystem root used by PHP for includes/requires, and a URL root used for links/assets. Relying on relative "../" paths becomes fragile once pages live in different subfolders. As hinted, server-provided values can help, but a more robust approach is to centralize the definition of both roots and use those everywhere.

Place a single config file at the project root and define an absolute filesystem path and a base URL there. For example, construct a normalized filesystem root from the config file location and keep a simple BASE_URL for link generation. Then all includes use the filesystem root and all HTML uses the base URL. This removes the need to edit relative dots when a file is moved.

Benefits and caveats: using a compile-time directory anchor (magic constants) plus a normalizer like realpath gives stable filesystem paths even with symlinks or different working directories. Defining the public base URL explicitly avoids surprising behavior behind proxies or when host headers differ between environments. For automated detection see PHP docs on magic constants and realpath for details and edge cases:

Troubleshooting checklist: ensure the config file is required early (so all scripts use the same constants), confirm server document root vs repository layout, and update BASE_URL if the site runs in a subfolder or under a different virtual host. Server-supplied environment values can be used as a fallback, but prefer an explicit config value for production. See the PHP server variables reference for what the server exposes.

Recommended Answers

All 2 Replies

$_SERVER will give you the root address.

Hmm.. It appears that didn't work, so I used $_SERVER["SERVER_NAME"], and it started working! Anyway, thanks for the help :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.