How to detect if a file is being included or directly ran

前端 未结 6 932
春和景丽
春和景丽 2021-01-20 00:09

I have a php file that I include in my php script, but I don\'t want people to be able to directly run the file(without being included). How can I prevent that from happenin

6条回答
  •  花落未央
    2021-01-20 00:47

    2 solutions for a good protection:

    1. Apache

    with htaccess:

    RedirectMatch 404 "\.(sql|sh|java|class|inc\.php)$"
    

    Or in /etc/apache2/sites-enabled:

    
    #...
    RedirectMatch 404 "\.(sql|sh|java|class|inc\.php)$"
    #...
    
    

    Then name your file like this: myInternalFileIncludeOnly.inc.php

    1. PHP

    With this sample code, PHP is able to detect include:

    if( get_included_files()[0] == __FILE__ ){
        echo '2.php direct access';
    }else{
        echo '2.php was included';
    }
    

    EDIT: See Tim answer, so if you have a prepend include (cf php.ini) use this:

    if(
        (!ini_get('auto_prepend_file') && get_included_files()[0] === __FILE__)
        ||
        ini_get('auto_prepend_file') && (($__FILE__=str_replace('\\','/',__FILE__)) === str_replace('\\','/',$_SERVER['DOCUMENT_ROOT'].$_SERVER['SCRIPT_FILENAME']) || $__FILE__ === str_replace('\\','/',$_SERVER['SCRIPT_FILENAME']) )
    )
        echo '2.php direct access',"\n";
    

提交回复
热议问题