phpincluderequire

PHP $_SERVER['DOCUMENT_ROOT'] removed a slash


I read other posts about $_SERVER['DOCUMENT_ROOT'] (like Where to set PHP $_SERVER['DOCUMENT_ROOT'] Trailing Slash?) but what happened to me is that all the pages in my website basically lost the slash overnight.

I didn't change anything either to the pages or the config files... What can I have done wrong to trigger this?

Is there a faster way to solve it than just update every single page? I use $_SERVER['DOCUMENT_ROOT'] . '/folder/library.php' pretty much in every file, so it's going to take a while (and a lot of pages not working) before to correct them all.


Solution

  • Create a central configuration file that normalizes the $_SERVER['DOCUMENT_ROOT'] and includes it in all your PHP files. This way, you only need to update the normalization logic in one place.

    config.php

    <?php
    // Normalize DOCUMENT_ROOT to ensure it always has a trailing slash
    $documentRoot = rtrim($_SERVER['DOCUMENT_ROOT'], '/') . '/';
    ?>
    

    Then, include this configuration file at the top of every PHP file:

    <?php
    require_once 'config.php';
    require_once $documentRoot . 'folder/library.php';
    ?>
    

    Create a utility function to handle the normalization of paths and use this function throughout your code.

    utils.php:

    <?php
    function getDocumentRoot() {
        return rtrim($_SERVER['DOCUMENT_ROOT'], '/') . '/';
    }
    ?>
    

    include this utility file and use the function

    <?php
    require_once 'utils.php';
    require_once getDocumentRoot() . 'folder/library.php';
    ?>