You are hereHome / Development / Don't trust PHP_SELF

Don't trust PHP_SELF


By Gerd Riesselmann - Posted on 11 January 2006

Sean Coates points out why $_SERVER["PHP_SELF"] must be considered unsafe. You should never use it without at least converting it to entities:

<?php
print htmlentities($_SERVER['PHP_SELF']);
?>

This offers me the chance to again repeat one of my mantras: Create a function for everything, at least when reading values from somewhere, even for something simple like retrieving the value of PHP_SELF. The reason is maintenance: If you haven't previously validated the value of PHP_SELF there will be only one place to change, instead of checking all your code.

Here's my implementation:

<?php
/**
* Static returns the recent URL.
*
* @param Boolean Indicated if query string (?...) should be included or not
* @returns String
*/
function recentURL($includeParams)
{
 
$http = "";
  if (
$includeParams)
  {
   
$http = $_SERVER["REQUEST_URI"];
  }
  else
  {
   
$http = $_SERVER["PHP_SELF"];     
  }
  return
toSafeURL($http);
}
/**
* Static. Processes an URL to strip of possible injection code
*
* @param String The URL to process
* @return String The cleaned URL
*/
function toSafeURL($url)
{
  return
htmlentities(strip_tags($url));
}
?>

Thanks,

I'm going to use that:)

Topics