Prevent direct access to a php include file

2018-12-31 10:19发布

I have a php file which I will be using as exclusively as an include. Therefore I would like to throw an error instead of executing it when it's accessed directly by typing in the URL instead of being included.

Basically I need to do a check as follows in the php file:

if ( $REQUEST_URL == $URL_OF_CURRENT_PAGE ) die ("Direct access not premitted");

Is there an easy way to do this?

30条回答
情到深处是孤独
2楼-- · 2018-12-31 10:22
if (basename($_SERVER['PHP_SELF']) == basename(__FILE__)) { die('Access denied'); };
查看更多
牵手、夕阳
3楼-- · 2018-12-31 10:22

Earlier mentioned solution with PHP version check added:

    $max_includes = version_compare(PHP_VERSION, '5', '<') ? 0 : 1;
    if (count(get_included_files()) <= $max_includes)
    {
        exit('Direct access is not allowed.');
    }
查看更多
栀子花@的思念
4楼-- · 2018-12-31 10:23

You can use phpMyAdmin Style:

/**
 * block attempts to directly run this script
 */
if (getcwd() == dirname(__FILE__)) {
    die('Attack stopped');
}
查看更多
美炸的是我
5楼-- · 2018-12-31 10:25

Actually my advice is to do all of these best practices.

  • Put the documents outside the webroot OR in a directory denied access by the webserver AND
  • Use a define in your visible documents that the hidden documents check for:
      if (!defined(INCL_FILE_FOO)) {
          header('HTTP/1.0 403 Forbidden');
          exit;
      }

This way if the files become misplaced somehow (an errant ftp operation) they are still protected.

查看更多
像晚风撩人
6楼-- · 2018-12-31 10:25
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

will do the job smooth

查看更多
泪湿衣
7楼-- · 2018-12-31 10:26

The easiest way is to store your includes outside of the web directory. That way the server has access to them but no outside machine. The only down side is you need to be able to access this part of your server. The upside is it requires no set up, configuration, or additional code/server stress.

查看更多
登录 后发表回答