Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blocking direct access

Tags:

php

How can direct access to certain pages be blocked without modifying .htaccess?

Is there a way to achieve that with some code inside each script?

Any help will be much appreciated.

like image 200
PDR Avatar asked Feb 19 '23 10:02

PDR


1 Answers

Try adding this code at first line:

Following Michael Berkowski suggestion, an improved version of the answer would be like this:

/***************DO NOT ALLOW DIRECT ACCESS************************************/
if ( (strpos( strtolower( $_SERVER[ 'SCRIPT_NAME' ] ), strtolower( basename( __FILE__ ) ) ) ) !== FALSE ) { // NOT FALSE if the script's file name is found in the URL 
  header( 'HTTP/1.0 403 Forbidden' );
  die( '<h2>Direct access to this page is not allowed.</h2>' );
}
/*****************************************************************************/

UPDATE:

/***************DO NOT ALLOW DIRECT ACCESS************************************/
if ( stripos( $_SERVER[ 'REQUEST_URI' ], basename( __FILE__ ) ) !== FALSE ) { // TRUE if the script's file name is found in the URL
  header( 'HTTP/1.0 403 Forbidden' );
  die( "<h2>Forbidden! You don't have permission to access this page.</h2>" );
}
/*****************************************************************************/

This code can be used to protect files with functions, classes, etc., used by other code, which don't need to be accessed through the browser. Such as most WP plugins, admin and include files, wp-config.php, functions.php; files to fetch data transferred via POST method (Not GET), etc.

like image 106
Felipe Alameda A Avatar answered Feb 27 '23 09:02

Felipe Alameda A