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.
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>' );
}
/*****************************************************************************/
/***************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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With