title: Setting the path for include / require files
body: <p>All my PHP include files are in a single directory:</p>
  
  <pre><code>https://www.mywebsite.com/includes
  </code></pre>
  
  <p>Inserting these files in top level pages is easy  enough:</p>
  
  <pre><code>&lt;?php include 'includes/logo.php'; ?&gt;
  &lt;?php include 'includes/main_nav.php'; ?&gt;
  &lt;?php include 'includes/news.php'; ?&gt;
  etc.
  </code></pre>
  
  <p>For sub-directory pages I've been doing this:</p>
  
  <pre><code>&lt;?php include '../includes/logo.php'; ?&gt;
  &lt;?php include '../includes/main_nav.php'; ?&gt;
  &lt;?php include '../includes/news.php'; ?&gt;
  </code></pre>
  
  <p>and this:</p>
  
  <pre><code>&lt;?php include '../../includes/logo.php'; ?&gt;
  &lt;?php include '../../includes/main_nav.php'; ?&gt;
  &lt;?php include '../../includes/news.php'; ?&gt;
  </code></pre>
  
  <p>So far so good, but I suspected it wasn't going to continuing being this easy.</p>
  
  <p>Now I need to include this file:</p>
  
  <pre><code>top_five_news_stories.php
  </code></pre>
  
  <p>in this:</p>
  
  <pre><code>news.php
  </code></pre>
  
  <p>At this point, my relative path strategy fails because the include in the include can have only one path structure.</p>
  
  <p>I've read several posts recommending absolute paths using:</p>
  
  <ul>
  <li><code>dirname(__FILE__)</code></li>
  <li><code>realpath(dirname(__FILE__)</code></li>
  <li><code>$_SERVER["DOCUMENT_ROOT"]</code></li>
  </ul>
  
  <p>However, they all come with some kind of caveat relating to PHP configuration, server configuration or operating system. In other words, there's often a comment by somebody saying it didn't work in their case, or doesn't work in IIS, or doesn't work in UNIX, or something else.</p>
  
  <p>A solution I haven't seen is one I thought would be most simple: Just set a variable:</p>
  
  <pre><code>$base = "https://www.mywebsite.com/includes";
  </code></pre>
  
  <p>then:</p>
  
  <pre><code>&lt;?php include $base . "logo.php" ?&gt;
  </code></pre>
  
  <p>Considering that I already use the <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base" rel="nofollow">HTML <strong><code>base</code></strong> element</a>, which works in a similar way, this method strikes me as simple and efficient.</p>
  
  <p>But since it wasn't mentioned in any of the posts I read, I'm wondering if I'm overlooking a potential problem.</p>
  
  <p>Frankly, if I had to go to production to today, I would use this:</p>
  
  <pre><code>&lt;?php include  $_SERVER['DOCUMENT_ROOT'] . '/logo.php" ?&gt;
  </code></pre>
  
  <p>which works for me and is commonly mentioned.</p>
  
  <p>But I'm wondering if using a variable is a reliable, efficient method?</p>