Protecting PHP file from direct access

I have been reading some WordPress PHP code on GitHub and I found that the author (a Senior WordPress developer) was putting this line of code in the beginning of each file:

defined('ABSPATH') or die("Cannot access pages directly.");

How does this protect the file from direct access? Can’t a hacker just define the constant ABSPATH and then load the file?

Read More

Also, why is direct access dangerous?

Related posts

Leave a Reply

4 comments

  1. This constant is probably set in the main WordPress PHP file, so if it’s not set, then you aren’t accessing the main page.

    Constants aren’t something a user can modify, they are in the code, and can only be changed by editing the PHP file. So, if a hacker could set this constant, then you’d have bigger problems, because that would involve him actually editing your PHP files.

    Direct access may not be dangerous (don’t quote me), but it’s pointless. Directly accessing a WordPress plugin (for example) won’t do anything, as the plugin needs to run through WordPress.

  2. defined('ABSPATH') or die("Cannot access pages directly.");   
    

    this constant is defined in the root files like index.php.
    it’s for check if ABSPATH is defined so this file is included with root or other file.
    and not direct access with URL .
    this way is one of the best ways to protect files from direct access

  3. Normaly you can’t declare serve-side variables so it is secure.

    Most probably an other page set that variable by some criteria, (pass verification , ip or anything you want)

    As said that page alone wont work because it need to read that variable from someware (an include or the page is included-in)

  4. Direct access can be dangerous – as the hacker can work out your business logic and possibly find ways around it (aka things that are not written in the code to protect yourself).

    Another possibility is that things are hard coded into the program that may result in direct access to databases, gaining knowledge of your network, etc…