简体   繁体   中英

javascript string replace equivalent on php?

I am trying to prevent xss injection. So before I submit a form, a javascript function is called

function validatefield(id) {
    var description = document.getElementById(id).value;   
    description = description.replace(/[\"\'][\s]*javascript:(.*)[\"\']/gi, "");
    description = description.replace(/script(.*)/gi, "");    
    description = description.replace(/eval\((.*)\)/gi, "");
    document.getElementById(id).value=description;
} 

I am wonderng if there's a way to do the same in php before inserting into the mysql? if they get around of the validatefield function.

Thanks

您正在寻找preg_replace

$description = preg_replace('regex pattern', 'regex replacement', $description);

Generally speaking, you can use preg_replace for regex replacements in PHP. But there are a few problems with your design

  1. You shouldn't even bother doing this on the client. It will slow things down without providing security.
  2. You're removing things that are perfectly safe (eg "I wrote a script to do such as such"), while ignoring many actual dangers like onclick attributes (see also XSS Cheat Sheet ).

Generally speaking, if you want to allow some form of HTML, a whitelist is a better approach. HTML Purifier is a popular tool for implementing this in PHP.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM