简体   繁体   中英

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

如果有必要将私有文件保留在公用文件夹中,则可以使用CHMOD权限(例如700)对其进行保护

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM