Jump to content


Photo

Code snippet for protection against PHP_SELF injections attacks.


  • Please log in to reply
No replies to this topic

#1 Christian F.

Christian F.

    Advanced Member

  • Staff Alumni
  • 3,106 posts
  • LocationNorway

Posted 08 August 2012 - 03:34 PM

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. :-)
Keeping it simple.




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users

Cheap Linux VPS from $5
SSD Storage, 30 day Guarantee
1 TB of BW, 100% Network Uptime

AlphaBit.com