How to know if php script is called via require_on

2019-02-15 14:24发布

My webapp has a buch of modules. Each module has a 'main' php script which loads submodules based on a query sent to the main module:

//file: clientes.php

//check for valid user...
//import CSS and JS...

switch( $_GET["action"] )
{
    case "lista" :          require_once("clientes.lista.php"); break;
    case "listaDeudores" :  require_once("clientes.listaDeudores.php"); break;
    case "nuevo" :          require_once("clientes.nuevo.php"); break;
    case "detalles" :       require_once("clientes.detalles.php"); break;
    case "editar" :         require_once("clientes.editar.php"); break;         
    default : echo "<h1>Error</h1><p>El sitio ha encontrado un error.</p>";
} 

This main module deals with security and imports many resources all submodules need. The big problem shows up when a user asks for any of the submodules, bypassing all the security measures on the main module! My idea was to add a line on every submodule to test if it was being called directly and deny access or if its been called via another script, and continue. The least thing I would like to do is redo the security checking on every single file, since it does a bunch of query's to the database.

Does a php script know if its been called via a require_once() or a direct call ? I've been trying to implement some sort of $_SERVER['REQUEST_URI'] and $_SERVER['PHP_SELF'] pitfall but I was wondering if there was some sort of an elegant way of doing this.

11条回答
贪生不怕死
2楼-- · 2019-02-15 14:50

A generic way that works without having to define a constant or use htaccess or use a specific directory structure or depend on the $_SERVER array that could theoretically be modified is to start each include-only (no direct access) file with this code:

<?php $inc = get_included_files(); if(basename(__FILE__) == basename($inc[0])) exit();
查看更多
戒情不戒烟
3楼-- · 2019-02-15 14:50

As practice of habit I have a console class built to send messages, errors, etc. to console with FirePHP. Inside the Console class write() method I have a check to see if a $_REQUEST[debug] == 1, that way I'm not exposing errors to users if something pops up on production and they would have to know what the request variable is to access the debug information.

At the top of every file I add:

Console::debug('fileName.php is loaded.');

here is a snippit from it to give you the right idea:

class Console{

  public static function write($msg,$msg_type='info',$msg_label=''){
    if(isset($_REQUEST['debug']) && $_REQUEST['debug'] == 'PANCAKE!'){
      ob_start();
      switch($msg_type){
        case 'info':
          FB::info($msg, $msg_label);
          break;
        case 'debug':
          FB::info($msg, 'DEBUG')
          break;
          ...
      }
    }
  }

  public static function debug($msg){
    Console::write($msg, '');
  }
}
查看更多
叛逆
4楼-- · 2019-02-15 14:51

One popular method to make sure modules are not called directly is defining a constant in the main script, and checking for that constant in the module.

// index.php
define("LEGIT_REQUEST", true);

// in each module
if (!defined("LEGIT_REQUEST")) 
  die ("This module cannot be called directly.");
查看更多
Summer. ? 凉城
5楼-- · 2019-02-15 14:51

An alternative to defining a constant and checking it is to simply put the files that index.php includes outside of the document root area. That way the user can't directly access them via your web server at all. This is also obviously the most secure way, in case your web server has a configuration error in future that eg. displays PHP files as plain text.

查看更多
仙女界的扛把子
6楼-- · 2019-02-15 14:52

Short and simple (for CLI):

if (__FILE__ == realpath($argv[0]))
    main();
查看更多
劳资没心,怎么记你
7楼-- · 2019-02-15 14:53

I was looking for a way to determine if a file have been included or called directly, all from within the file. At some point in my quest I passed through this thread. Checking various other threads on this and other sites and pages from the PHP manual I got enlightened and came up with this piece of code:

if ( basename(__FILE__) == basename($_SERVER["SCRIPT_FILENAME"]) ) {
  echo "called directly";
}

else {
  echo "included/required"
}

In essence it compares if the name of the current file (the one that could be included) is the same as the file that is beeing executed.


EXPLANATION:

  • __FILE__ is a PHP magic constant that stores the full path and filename of the file, the beauty of it is that if the file has been included or required it still returns the full path and filename of such file (the included file).
    (Magic Constants Manual: http://php.net/manual/en/language.constants.predefined.php)

  • $_SERVER["SCRIPT_FILENAME"] returns the absolute pathname of the currently executing script. As when a file is included/required it's not executed (just included) it returns the path name of the (let's say) "parent" file (the one that includs the other file and the one that gets executed).

  • basename(string $path) is a function that returns the trailing name component of path, that in this case is the file name. You could also just compare the full path and filename, that would be indeed better, it isn't really neceseary to use this function but it feels cleaner this way, jajaj.
    (basename(): http://php.net/manual/en/function.basename.php)

I know it's a "bit" late to be answering the main question but I guessed that it could be useful to anyone who's on the same situation that I was and that also passes by.

查看更多
登录 后发表回答