r/PHPhelp • u/edhelatar • Oct 23 '25
Escaping html attribute name
Hey. I have a weird thing that I never had to deal with in my quite long career.
How the hell do you escape html attribute names?
As in I have a function that renders html attributes
function(array $data): string {
$str = '';
foreach ($data as $key => $value) {
$esc = htmlspecialchars($value,
ENT_QUOTES
|
ENT_SUBSTITUTE
);
$str .= sprintf(' %s="%s"', $key, $esc);
}
return $str;
}That's all cool. But if the key in $data gonna be something like `onload="stealGovernmentSecrets()" data` then it will execute a malicious script.
I did try to Google that, but it seems that all the answers are about escaping values, not keys.
Any ideas? I really don't want to go through html spec and implement something that probably gonna end up being insecure either way :)
View all comments
Show parent comment
1
u/edhelatar Oct 24 '25
Not really future proof. New html elements attributes are added all the time as well as there's Infinite amount of custom ones. It's for twig extension so I don't want to stop other developers to have to wait for or to use new element