Will this work?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
seodevhead
Forum Regular
Posts: 705
Joined: Sat Oct 08, 2005 8:18 pm
Location: Windermere, FL

Will this work?

Post 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.
User avatar
shiznatix
DevNet Master
Posts: 2745
Joined: Tue Dec 28, 2004 5:57 pm
Location: Tallinn, Estonia
Contact:

Post by shiznatix »

nope, that is perfect. run with it
User avatar
php3ch0
Forum Contributor
Posts: 212
Joined: Sun Nov 13, 2005 7:35 am
Location: Folkestone, Kent, UK

Post by php3ch0 »

what would the reverse of this be?
User avatar
Maugrim_The_Reaper
DevNet Master
Posts: 2704
Joined: Tue Nov 02, 2004 5:43 am
Location: Ireland

Post 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...
matthijs
DevNet Master
Posts: 3360
Joined: Thu Oct 06, 2005 3:57 pm

Post 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.
Post Reply