Page 1 of 1

Will this work?

Posted: Mon Feb 20, 2006 4:52 pm
by seodevhead
Hey guys... I am testing out a function I just wrote and it seems to be working fine, but I wanted to show it to you guys to make sure I don't have any flaws or that I am overlooking something.

Since I have to output a lot of variables to the client in php, I always have to constantly type:

Code: Select all

$var = 'test'
echo stripslashes(htmlentities($var, ENT_QUOTES, 'UTF-8'));
But I don't want to have to write out the whole 'stripslashes....entites..ENT_QUO's, etc'... so I made a function to do it for me:

Code: Select all

function outputThis($outputString)
{
	$sendToBrowser = stripslashes(htmlentities($outputString, ENT_QUOTES, 'UTF-8'));
	return $sendToBrowser;
}
Thus all I have to do to output a variable to the client is:

echo outputThis($var);

Do any of you guys see any problems with my code? I want to make sure I leave no stone unturned since I am putting it up live for public. Thanks for your review.

Posted: Mon Feb 20, 2006 6:03 pm
by shiznatix
nope, that is perfect. run with it

Posted: Tue Feb 21, 2006 5:59 am
by php3ch0
what would the reverse of this be?

Posted: Tue Feb 21, 2006 6:09 am
by Maugrim_The_Reaper
When are the slashes added? Not all PHP servers will have magic_quotes_gpc enabled is that's the root cause... Might be good to stripslashes from all form/uri input variables from the start, then just escape as normal using htmlentities() for browser output and mysql_real_escape_string() (or other DBMS equivalents) for SQL insertion.

Just a thought since this might cause problems where addslashes() is not automatically applied by PHP...

Posted: Tue Feb 21, 2006 8:54 am
by matthijs
A function to undo magic quotes in case they are enabled:

Code: Select all

// from php Architect's Guide to PHP Security, Ilia Alshanetsky
if (get_magic_quotes_gpc()) {
  $in = array(&$_GET, &$_POST, &$_COOKIE);
  while (list($k,$v) = each($in)) {
      foreach ($v as $key => $val) {
           if (!is_array($val)) {
                $in[$k][$key] = stripslashes($val);
                continue;
           }
           $in[] =& $in[$k][$key];
      }
  }
  unset($in);
}
You can include this in the top of every script. Then you never have to use stripslashes or addslashes anymore.