WordPress-Coding-Standards: Check for ABSPATH exit

Is your feature request related to a problem?

To avoid direct file access, a lot of WP files disallow access if ABSPATH is not defined. Since this essentially useful for all files that are used in the WP ecosystem, there should be a sniff for this (& perhaps even an auto-fix)

Describe the solution you’d like

if a file does not contain:

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly
}

before any other PHP code, EXCEPT if the file contains a require_once for wp-load (which would load the ABSPATH), it should give an error.

About this issue

  • Original URL
  • State: open
  • Created 7 years ago
  • Comments: 17 (8 by maintainers)

Most upvoted comments

Hi, @remcotolsma thanks for collecting all the information and push it to be part of PHPCS.

Also thanks to @GaryJones , I’ve already changed the message to make it more specific in that line.

You can avoid this by putting this code at the top of all php files that could potentially execute code if accessed directly:

Hi @jrfnl and congrats for the new PHPCS version and your contribution to it, I’m eager to try it. We’ve been working fast on some automations to make the team work faster on the reviews, I did this internal check and, as for now, sadly I don’t have either the time or the knowledge to make it to PHPCS, but I’ll be really happy to contribute, and I think improving and maintaining PHPCS would be so good for the plugins team.

@remcotolsma I think it would be useful for the community if such checks were not scattered across different repos, so the plugin team may want to consider contributing to WPCS…

Actually, the defined() check is essentially a nonsense-check unless the file gives direct output.

So for things like views or the main plugin file this can be considered good practice.

But for files which only contain classes or function definitions, it’s a bit nonsensical as no code is being run until it is actively called from somewhere else.