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:
Some of your aspirations tend to be pretty unrealistic. You pride yourself on being a rational thinker. You have a tendency to be critical of yourself.
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!
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.6 green bottles hanging on the wall,
6 green bottles hanging on the wall,
And if one green bottle should accidentally fall,
There'll be 5 green bottles hanging on the wall.5 green bottles hanging on the wall,
5 green bottles hanging on the wall,
And if one green bottle should accidentally fall,
There'll be 4 green bottles hanging on the wall.4 green bottles hanging on the wall,
4 green bottles hanging on the wall,
And if one green bottle should accidentally fall,
There'll be 3 green bottles hanging on the wall.