Preventing direct access to includes

Following up on Lesson 4, this page provides a demonstration of two ways to prevent your visitors from directly accessing files that you intended to be used only with include or require statements:

Solution 1: keep the files outside of the webroot

Below, we use: <?php include('../private/sample-include.php'); ?> to include a file from outside the webroot. You can view the source code of that file (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 this page.

Your personality analysis:

You critically analyse yourself in your duties. You have a great deal of unused capacity which you have not turned to your advantage. Disciplined and self-controlled outside, you tend to be worrisome and insecure inside. You have found it unwise to be too frank in revealing yourself to others.

Solution 2: have your include files "halt early" if accessed directly

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.

Below, we use: <?php include('sample-include-2.php'); ?> to load a file from within the webroot. If you try to access it directly, via https://php.danq.dev/appendix-samples/sample-include-2.php , you won't see anything, but when it's included from this page, it outputs four verses of "10 Green Bottles". View the source code of that file to see how that trick is performed!

10 green bottles hanging on the wall,
10 green bottles hanging on the wall,
And if one green bottle should accidentally fall,
There'll be 9 green bottles hanging on the wall.

9 green bottles hanging on the wall,
9 green bottles hanging on the wall,
And if one green bottle should accidentally fall,
There'll be 8 green bottles hanging on the wall.

8 green bottles hanging on the wall,
8 green bottles hanging on the wall,
And if one green bottle should accidentally fall,
There'll be 7 green bottles hanging on the wall.

7 green bottles hanging on the wall,
7 green bottles hanging on the wall,
And if one green bottle should accidentally fall,
There'll be 6 green bottles hanging on the wall.