I think this best way to prevent direct access..

<?php if (!defined('ABSPATH')) { exit; }?>

i have used this on all my php files..can it create problems? any files on WordPress theme i should not use it?


The point of that code is to prevent any PHP inside the file from being executed if the file is accessed directly outside a WordPress context. ABSPATH is defined by WordPress, so if it's missing when the file is accessed you can tell that it's not running in a WordPress context.

So the only place you wouldn't use it is in any file that you did need to access directly. There probably shouldn't be any such files in a WordPress theme or plugin. The most common example might be a file for handling AJAX requests, but in WordPress you should be using admin-ajax.php or the REST API for that sort of thing.

|improve this answer|||||
  • hi, What about the class files with namespace it's not possible to put this code ? am i required to put this code there – Latheesh V M Villa Nov 16 '18 at 12:44
  • 1
    It just needs to go after the namespace declaration, but before the class. – Jacob Peattie Nov 16 '18 at 12:49

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.