I am trying to add some validation for the description field to check if the user has entered any scripting/js/jQuery/SQL query code rather than a genuine product description.
// Check for disallowed patterns (JavaScript, jQuery, and SQL)
$disallowedPatterns = array(
'/b(?:alert|confirm|prompt)bs*([^;]*)s*;/i' => 'JavaScript code (script tag)',
'/b(?:alert|confirm|prompt)s*([^)]*(?<!["']s*;))s*;/i' => 'JavaScript functions with parenthesis (alert, confirm, prompt)',
'/$([^)]*).?[a-z]+/i' => 'jQuery-related patterns',
'/b(?:select|insert|update|delete|union|where)b/i' => 'SQL keywords'
);
$codeDetected = false;
foreach ($disallowedPatterns as $pattern => $description) {
if (preg_match($pattern, $params['propertydescription'])) {
$codeDetected = true;
break;
}
}
if ($codeDetected) {
throw new Exception("Invalid input. The description contains disallowed content: $description");
}
But somehow, this is not working 100% for me.
I want to know if I am choosing the right way or if any third-party library can check/prevent the same.
2
Answers
Just turn on XSS Filtering (
application/config/config.php
)Or In validation like this
xss_clean
It will
<
,>
,"
,'
, and&
are converted into their HTML entities (like<
,>
,"
,'
, and&
)<script>
You can use filter_var to detect a pattern match, here is my implementation