What is meant by [if ( ! defined( 'ABSPATH' ) )]

It prevent public user to directly access your .php files through URL. Because if your file contains some I/O operations it can eventually be triggered (by an attacker) and this might cause unexpected behavior.

So, Using the snippets can prevent access from your files (directly) and ensures that your Theme files will be executed within the WordPress environment only.

Usage:

  1. It can be placed at the top of any of your PHP files (theme & plugin)
  2. It can be placed at the top of your wp-config.php

Hope it helps


ABSPATH is a PHP constant defined by WordPress at the bottom of wp-config.php:

/* That's all, stop editing! Happy blogging. */

/** Absolute path to the WordPress directory. */
if ( !defined('ABSPATH') )
    define('ABSPATH', dirname(__FILE__) . '/');

As you can see on the comment block above, WordPress does not recommend to modify these lines of code - probably because many plugins and themes rely on ABSPATH to verify if their PHP files are being executed within the WordPress environment.

If you use this snippet at the top of your wp-config.php file, you will terminate the execution of the wp-config.php, because ABSPATH has not been defined yet at that point. And other files that depend on wp-config.php will fail (i.e. you will break your website).

if ( ! defined( 'MY_CONSTANT' ) ) { exit; } is a snippet widely used by PHP files of plugins and themes only by convention. In theory, it means you can add your own constant at the bottom of your wp-config.php, and you will get the same practical result.

Your wp-config.php:

if ( !defined('MY_CONSTANT') )
    define('MY_CONSTANT', 'fool');

Your theme or plugin file:

<?php 
    if ( ! defined( 'MY_CONSTANT' ) ) {
        exit; // Exit if accessed directly
    }

More Info

Defining a constant in PHP: http://php.net/manual/en/language.constants.syntax.php

PHP magic constants: http://php.net/manual/en/language.constants.predefined.php

Tags:

Php

Wordpress