3
\$\begingroup\$

I am a PHP newbie and this is part of a gallery code. I recently read about SQL injection and cross site scripting attack, I am trying to avoid that by html escaping on dynamically produced data. I am not sure if I am heading in the right direction here. I created an array with URL parameters then a function for HTML escaping. Can you critique this code and let me know what I am doing wrong?

$parameters_new = array('name' => $name,'pcaption' => $caption_array[$new]);

function html_escape($input, $encoding)
{
    return htmlentities($input, ENT_QUOTES, $encoding);
}

$result_final .= '<div class="limage"><table><tr><td><table class="image"><tr><td><a href="' . html_escape('gallery.php?' . http_build_query($parameters_new), 'UTF-8') . '">
<img src="'. $img_dir . '/' .$photo_filename.'"  alt=" ' . $photo_keywords . '"></a>
<div class="caption">'.$photo_caption.'</div><div class="excerpt">'.$photo_description.'</div></td></tr></table></td></tr></table><div class="underline"></div>;
\$\endgroup\$
  • \$\begingroup\$ Given that the href attribute can't possibly contain < and > (at least not AFAIK), strip_tags seems like a valid contender. Also: http_build_query + additional escaping might put you at risk for double encoded values (like ` ` => %20 => %2520), so be careful \$\endgroup\$ – Elias Van Ootegem Sep 4 '14 at 13:09
1
\$\begingroup\$

Instead of a one size fits all approach, you can filter things based on what they are.

  • URLs and url parameters can be encoded with urlencode()
  • Output inside of html tags can be filtered with strip_tags()
  • Other more general output that you are using with HTML attributes such as 'alt' are less predictable, and can be filtered with htmlentities()
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.