Search code examples
phprequire

PHP require Link


When attempting to link from the root directory in my PHP file, I am unable to load the file. It works fine unless I add the file path as absolute, like so:

<link href="/supportfiles/subheader/css/css.css" rel="stylesheet" type="text/css">
  <div id="subheadingContainer">
    <div id="allContentContainer">
        <?php 

          if (count($loggedIn["directReports"]) != 0 ) {
            require("/supportfiles/subheader/itemshtml/inbox.php");
          } else {
            require("/supportfiles/subheader/itemshtml/myrequests.php");
          }

        ?>
  </div>
</div>

Any idea why it works fine if I ../ but not if I hard code it? This is a support heading file, so im using it across multiple levels in directories and I think it should be hard coded from the root.


Solution

  • When you use absolute paths in PHP, / refers to the root of your file system, not the root of your web application, this means that if you want to use absolute path you have to use the path as if you accessed from your file manager, not from the browser. For example lets say that you are working on linux with apache and that the root directory of your apache server is /var/www/ then you would have to put:

    require("/var/www/supportfiles/subheader/itemshtml/inbox.php");
    

    if you are unsure of your document root you can use the PHP's $_SERVER['DOCUMENT_ROOT']. so in your case just put $_SERVER['DOCUMENT_ROOT'] before any absolute path and this must work just fine. so for example:

    require $_SERVER['DOCUMENT_ROOT'] . '/supportfiles/subheader/itemshtml/inbox.php';