Jump to content

Code snippet for protection against PHP_SELF injections attacks.


Recommended Posts

Since I can't post this in the FAQ/Code Snippet Repository forum, I decided to post it here. Apologies if this breaks with the posting guidelines/standards here.

 

Anyway, I've seen quite a few posts here where people have used $_SERVER['PHP_SELF'] and gotten told to never do this, due to the HTML injection risk it carries with it.

While I do agree with the statement that PHP_SELF is unnecessary in most cases, there are situations where it's very useful. That's why I'm using the following snippet, to ensure that PHP_SELF is clean, and thus safe to use.

// Make sure that PATH_INFO is set, and not ORIG_PATH_INFO as some hosts seem to use.
if (isset ($_SERVER['ORIG_PATH_INFO']) && $_SERVER['ORIG_PATH_INFO'] != $_SERVER['PHP_SELF']) {
$_SERVER['PATH_INFO'] = $_SERVER['ORIG_PATH_INFO'];
}

// Security measure, to avoid XSS exploit.
if (!empty ($_SERVER['PATH_INFO']) && strrpos ($_SERVER['PHP_SELF'], $_SERVER['PATH_INFO'])) {
$_SERVER['PHP_SELF'] = substr ($_SERVER['PHP_SELF'], 0, -(strlen ($_SERVER['PATH_INFO'])));
}

 

Just put it at the top of your index/entrance file, and it'll clean the path of PHP_SELF from anything that's not the actual address to the file.

 

It's posted as "public domain", and I hope someone else finds it useful. :-)

Link to comment
Share on other sites

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.