Prevent direct access to a php include file

后端 未结 30 965
盖世英雄少女心
盖世英雄少女心 2020-11-22 06:32

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

相关标签:
30条回答
  • 2020-11-22 07:16

    You'd better build application with one entrance point, i.e. all files should be reached from index.php

    Place this in index.php

    define(A,true);
    

    This check should run in each linked file (via require or include)

    defined('A') or die(header('HTTP/1.0 403 Forbidden'));
    
    0 讨论(0)
  • 2020-11-22 07:16

    I didn't find the suggestions with .htaccess so good because it may block other content in that folder which you might want to allow user to access to, this is my solution:

    $currentFileInfo = pathinfo(__FILE__);
    $requestInfo = pathinfo($_SERVER['REQUEST_URI']);
    if($currentFileInfo['basename'] == $requestInfo['basename']){
        // direct access to file
    }
    
    0 讨论(0)
  • 2020-11-22 07:17
    <?php       
    $url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
      if (false !== strpos($url,'.php')) {
          die ("Direct access not premitted");
      }
    ?>
    
    0 讨论(0)
  • 2020-11-22 07:17
    if ( ! defined('BASEPATH')) exit('No direct script access allowed');
    

    will do the job smooth

    0 讨论(0)
  • 2020-11-22 07:18

    I wanted to restrict access to the PHP file directly, but also be able to call it via jQuery $.ajax (XMLHttpRequest). Here is what worked for me.

    if (empty($_SERVER["HTTP_X_REQUESTED_WITH"]) && $_SERVER["HTTP_X_REQUESTED_WITH"] != "XMLHttpRequest") {
        if (realpath($_SERVER["SCRIPT_FILENAME"]) == __FILE__) { // direct access denied
            header("Location: /403");
            exit;
        }
    }
    
    0 讨论(0)
  • <?php
    if (eregi("YOUR_INCLUDED_PHP_FILE_NAME", $_SERVER['PHP_SELF'])) { 
     die("<h4>You don't have right permission to access this file directly.</h4>");
    }
    ?>
    

    place the code above in the top of your included php file.

    ex:

    <?php
    if (eregi("some_functions.php", $_SERVER['PHP_SELF'])) {
        die("<h4>You don't have right permission to access this file directly.</h4>");
    }
    
        // do something
    ?>
    
    0 讨论(0)
提交回复
热议问题