PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
i'm trying to figure out how to retain slashes typed in form fields which are saved into a mysql database.
for e.g. if \\ is typed, \\ is saved. if \ is typed, \ is saved.
<?php
function safe($var){
$pattern = '/&(#)?[a-zA-Z0-9]{0,};/';
if (is_array($var)) { // If variable is an array
$out = array(); // Set output as an array
foreach ($var as $key => $v) {
$out[$key] = safe($v); // Run formspecialchars on every element of the array and return the result. Also maintains the keys.
}
} else {
$out = $var;
while (preg_match($pattern,$out) > 0) {
$out = htmlspecialchars_decode($out,ENT_QUOTES);
}
$out = htmlspecialchars(mysql_real_escape_string(trim($out)), ENT_QUOTES,'UTF-8',true);
}
return $out;
}
?>
mysql_real_escape_string() is meant to stop SQL injection. Htmlspecialchars is meant to stop Cross-Site-Scripting (XSS). For this situation, you don't need anything else. If you want to trim() it, that's fine, but it doesn't make your application more secure. If you want to strip HTML tags, you can do that if you want. That's for if you don't want any HTML in the string.
It's been more or less pointed out already, but if you use one generic "safe" function like this, you're making a big (but common) mistake. Strings from or for exactly WHAT are supposed to be made safe here??
Consider this: Stripping tags from input (GET or POST) strings, or escaping strings to put them in SQL queries, or convertings special characters to html entities to put them in HTML output, are three completely different things.