How to protect files from outside?
I've made a very small 开发者_如何转开发CMS myself. After login a session is set.
The CMS includes certain images, php pages, etc.
These pages may also include forms to add data to the database.
Now the problem is that you actually can use an address to get to the page which shows the form, ie;
domain.com/mycms/includes/addpage.php
How would you suggest to protect this?
NOTE: when I am logged in everything must work, just from outside it may not show the form. I could check if the session exists but I wonder if there are better and easier ways.
First of all, if you are including PHP files, you really should not place them inside your public web root.
If this is not possible, an alternative approach would be to define a constant in your index.php
(assuming you use this as a main entry point) and checking wether this constant is set in every include file in order to prevent direct access to these files.
For example:
// index.php:
define('INDEX_LOADED', true);
// /includes/addpage.php:
if (!defined('INDEX_LOADED')) die('no direct access allowed');
Aim to put your files in
domain.com/private/includes/addpage.php
And then from your page do something like
include('../private/includes/addpage');
I always use extension .inc.php for PHP files that should not be accessed from outside. Then I deny that extension to be visible from outside. For apache you can do this in .htaccess file in main directory:
<Files ~ "\.inc\.php$">
Order allow,deny
Deny from all
</Files>
Also if you use some framework or you have a class (or include) directory you can deny access to the whole directory like this (apache):
<Location ~ "^/(classes|framework)"
Order allow,deny
Deny from all
</Location>
Other web servers have other ways to forbid files. If you want it universal and portable - the Aron Rotteveel's suggestion is the best.
You can leave files that only contain classes declarations unprotected - if they are run from outside no code will run. Make sure that php ini setting display_errors is off for the host
If it necessary to keep private files inside public folder you can protect it with CHMOD permissions like 700
精彩评论