Home » Javascript » Ultimate chars to escape list for php, javascript and mysql

Ultimate chars to escape list for php, javascript and mysql

Posted by: admin November 1, 2017 Leave a comment

Questions:

Many sites uses php and javascript and mysql. I’d like to know the chars to escape, when and how, for the site security(not paranoid but good security)(and performance).
This is what I do now:
When saving user submited string:

//I set the utf8 charset everywhere
$str = urldecode($str);
$str = trim($_POST['name']);
if (mb_strlen($str, 'utf-8') <= $maxsize) //{...
//remove tab, null, backspace, controlz chars
$str = str_replace(array("\t","\x00","\x08","\x1a"),"",$str);
$str = str_replace(["%","_"],["\%","\_"],$str); // if I use like in the query
//I use prepared statement to insert in db, so i dont need to escape quotes and others
$stmt = $sql->prepare("INSERT INTO atable (acol) VALUES (?)");
$stmt->bind_param('s', $str);
$stmt->execute();

Now when displaying a string from the db, with php echo, that could also be javascript code and vars. I replace with entities these: <>&'”`\$%{}[]_; .

$a = array("<",">","&","'",'"',"\","$","%","_","{","}","[","]",";");
$b = array("&lt;","&gt;","&","'",""","\","$","%","_","{","}","[","]",";");
$str = str_replace($a,$b,$str);
echo $str;

Anything wrong? Missing or unnecessary chars ?

Updates
The left/right single/double quotation mark (like w3schools calls em) can be dangerous ???

Answers: