0

I found 2 ways to block direct access to php files (although it's not always necessary, see https://wordpress.stackexchange.com/a/63004/60539) The first one is:

defined( 'ABSPATH' ) or die( 'No script kiddies please!' );

And the other:

if ( ! empty( $_SERVER['SCRIPT_FILENAME'] ) && basename( __FILE__ ) == basename( $_SERVER['SCRIPT_FILENAME'] ) ) {
    die ( 'You do not have sufficient permissions to access this page!' );
}

Are they doing the same thing? Shall I prefer one to the other?

3

In my opinion, the only way to do this (within the context of WordPress) is:

if ( ! defined( 'ABSPATH' ) ) // Or some other WordPress constant
     exit;

The second technique is vague and does give the same level of checking (it only checks that the filename of the main PHP file matches itself, not whether WordPress is loaded, nor if it's another file of the same name).

And this No script kiddies please! is pointless, I wish this fad would die - just exit silently.

  • I've just noticed the second snippet logic is even more ludicrous - whilst the empty check ensures there's no undefined index errors, on setups that do not set SCRIPT_FILENAME (rare but it happens), the expression won't even evaluate and the script will try to run! – TheDeadMedic Jan 15 '16 at 10:01
1

The logic of the first one is based on wordpress setting ABSPATH as part of the initialization, and therefor if it was not set you are not accessing the site via the "official" wordpress end points.

The second seems to be a general PHP technique.

The best way is to just write code without side effects (or if you are the owner of the site block access to any php file in htaccess), but if you must I would say go with the first one as it is assumes some wordpress specific execution path.

  • The best approach is a combination of both approaches - write code without side effects and prevent direct file access. – rinogo Aug 11 '18 at 15:25
  • @rinogo technically you can not do htaccess as a developer of a theme or plugin, you just have very little or no control at all about that file (for example the site might run on nginx) – Mark Kaplun Aug 11 '18 at 15:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.