Prevent Direct Access to ! index.php

Discussions of secure PHP coding. Security in software is important, so don't be afraid to ask. And when answering: be anal. Nitpick. No security vulnerability is too small.

Moderator: General Moderators

Post Reply
Hermit TL
Forum Commoner
Posts: 69
Joined: Mon Nov 21, 2011 12:16 am

Prevent Direct Access to ! index.php

Post by Hermit TL »

I'm working on a site where are scripts are loaded through index.php
What is the best way to prevent people from accessing other scripts on the site directly?
I'm currently using something like this:

Code: Select all

if (security_filter($_SERVER['PHP_SELF'],"string") != "/index.php"){ echo "ACCESS DENIED"; exit(); }
Don't worry about security_filter() so basically I'm using:

Code: Select all

if ($_SERVER['PHP_SELF'] != "/index.php"){ echo "ACCESS DENIED"; exit(); }
in every page to prevent people from directly accessing other scripts.
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: Prevent Direct Access to ! index.php

Post by pickle »

Use mod_rewrite to redirect all requests to index.php (except maybe image files & css files). In your index.php file, you can check in $_SERVER what page he person was actually requesting and go from there.

Also, PHP_SELF may not always be set so it's not 100% safe to use. In most cases you can accomplish the same with $_SERVER['SCRIPT_NAME']
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
User avatar
McInfo
DevNet Resident
Posts: 1532
Joined: Wed Apr 01, 2009 1:31 pm

Re: Prevent Direct Access to ! index.php

Post by McInfo »

Ideally, you would store sensitive scripts outside the document root so they could not be accessed over HTTP. If your host does not give you access to such a directory, you can put your scripts in a private directory which is password-protected.

Apache HTTP Server: Authentication, Authorization and Access Control
Post Reply