Source Code for /public/appendix-samples/includes-from-outside-webroot.php

<h1>Preventing direct access to includes</h1>
<p>
  Following up on <a href="/04-includes-and-functions/">Lesson 4</a>, this page
  provides a demonstration of two ways to prevent your visitors from directly
  accessing files that you <em>intended</em> to be used only with
  <code>include</code> or <code>require</code> statements:
</p>

<h2>Solution 1: keep the files outside of the webroot</h2>
<p>
  Below, we use: <code>&lt;?php include('../private/sample-include.php'); ?&gt;</code>
  to include a file from outside the webroot. You can
  <a href="/source-viewer.php?file=private/sample-include.php">view the source
  code of that file</a> (but only because this site explicitly allows you to,
  of course!). But there does not exist any web address that would load it directly.
  The only way to run it is from <em>this</em> page.
</p>
<?php include('../../private/sample-include.php'); ?>

<h2>Solution 2: have your include files "halt early" if accessed directly</h2>
<p>
  If you can't, or don't want to, store your include files outside of the webroot,
  but still don't want them to be accessed directly by their web addresses, you
  can have them "halt early" if accessed directly.
</p>
<p>
  Below, we use: <code>&lt;?php include('sample-include-2.php'); ?&gt;</code> to
  load a file from within the webroot. If you try to access it directly, via
  <a href="https://php.danq.dev/appendix-samples/sample-include-2.php">
    https://php.danq.dev/appendix-samples/sample-include-2.php
  </a>, you won't see anything, but when it's included from <em>this</em> page,
  it outputs four verses of "10 Green Bottles".
  <a href="/source-viewer.php?file=public/appendix-samples/sample-include-2.php">
    View the source code of that file
  </a> to see how that trick is performed!
</p>
<?php include('sample-include-2.php'); ?>