How can one convert an absolute path obtained from the __FILE__ constant to a path relative to the root directory in PHP?

When working with file paths in PHP, it is common to encounter absolute paths obtained from the __FILE__ constant. If you need to convert this absolute path to a path relative to the root directory, you can achieve this by using the realpath() function along with the dirname() function. This combination allows you to determine the root directory and then calculate the relative path from there.

// Get the absolute path using __FILE__
$absolutePath = __FILE__;

// Get the root directory path
$rootDirectory = realpath($_SERVER["DOCUMENT_ROOT"]);

// Calculate the relative path from the root directory
$relativePath = str_replace($rootDirectory, "", $absolutePath);

echo $relativePath;