Worthwhile to restrict direct access of theme files?

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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x