I've run across the following snippet in themes from time to time:

if ( ! defined('ABSPATH')) exit('restricted access');

It's at the beginning of some (all?) PHP files in a theme and it's supposed to prevent direct access of the file by nefarious sources.

I see that this isn't included in Twenty Ten or Eleven and I've never seen it recommended in official WordPress documentation. It seems like a good idea to me, but I also don't know enough about security to judge it and can't find much with Google.

Is this something I should have in my custom themes? If so, should it be in all PHP files or just some?

  • 7
    Just for later readers, this can be written shorter and nicer: defined('ABSPATH') OR exit;
    – kaiser
    Commented Jan 14, 2013 at 16:16
  • or even shorter: defined('WPINC') ? : die(); :P
    – Tim Elsass
    Commented May 11, 2017 at 13:19
  • I also wonder if it worth putting in some code like this just to avoid seeing the PHP errors about undefined functions in my error logs. Bots seem to like to directly hit these files sometimes and I get errors like 'Call to undefined function query_posts()' because the WP bootstrap hasn't been loaded
    – Matt Keys
    Commented Dec 27, 2018 at 19:57

1 Answer 1


Usually, you don’t need it. But … there is at least one edge case:

  • If a theme file is a template part,
  • and it is using global variables from the calling context (parent file),
  • and register_globals is on,
  • and it is just using these variables without any security check …

… an attacker can call this file, set the missing variables with GET or POST and make the theme file print those out. And then there is a security problem.

So … the best option is not a context check like the one from your example, but good code: avoid global variables, check their content before you print it out.

  • If a template part still contained at least one function call that would cause a PHP fatal error would this scenario still be possible?
    – Chris_O
    Commented Aug 25, 2012 at 4:52
  • @Chris_O Depends on the order of appearance.
    – fuxia
    Commented Aug 25, 2012 at 4:57
  • 1
    It's always best to be safe than sorry. Too much security can't hurt, can it?
    – Sean Berg
    Commented Aug 25, 2012 at 17:41
  • 3
    If you do everything right, you should not use code that isn’t needed. This question is the proof that it makes code harder to follow.
    – fuxia
    Commented Aug 25, 2012 at 17:45
  • 1
    @GerardReches Yes, exactly. :)
    – fuxia
    Commented Apr 12, 2021 at 11:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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