Search code examples
phpforeachhtmlspecialchars

Is a foreach loop on $_GET a good way to apply htmlspecialchars?


I'm wondering if there is a significant downside to using the following code:

if(isset($_GET)){
foreach($_GET as $v){
    $v = htmlspecialchars($v);
}
}

I realize that it probably isn't necessary to use htmlspecialchars on each variable. Anyone know offhand if this is good to do?

UPDATE:

Because I don't think my above code would work, I'm updating this with the code that I'm using (despite the negativity towards the suggestions). :)

if(isset($_GET)){
foreach($_GET as $k=>$v){
    $_GET[$k] = htmlspecialchars($v);
}
}

Solution

  • This totally depends on what you want to do.

    In general, the answer is "no", and you should only escape data specifically for their intended purpose. Randomly escaping data without purpose isn't helping, and it just causes further confusion, as you have to keep track of what's been escaped and how.

    In short, keep your data stored raw, and escape it specifically for its intended use when you use it:

    • for HTML output, use htmlentities().
    • for shell command names, use escapeshellcmd().
    • for shell arguments, use escapeshellarg().
    • for building a GET URL string, use urlencode() on the parameter values.
    • for database queries, use the respective database escape mechanism (or prepared statements).

    This reasoning applies recursively. So if you want to write a link to a GET URL to the HTML output, it'd be something like this:

    echo "<a href=" . htmlentities("$url?q=" . urlencode($var)) . ">click</a>";
    

    It'd be terrible if at that point you'd have to remember if $var had already previously been escaped, and how.