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
2 solutions for a good protection:
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
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";