I am learning, and I put the snippet below into a formmail script so it would accept only safe characters. But when I test it, all other characters such as & * % also go through to the the text file it writes to, and to the email the formmail.php sends it to. What am I doing wrong on this thing?
will delete all characters that are not simple letters and numbers.
However, whatīs save and what isnīt will depend on the context. When you output the input as HTML then htmlspecialchars [php.net] is all you really need to make sure that the output is save. When you pass the input to the shell you might want to use escapeshellcmd [php.net]. The method you suggested is rather brute force and eliminates more than really necessary in most cases.
Most of the time when I do data checking I use specific patterns/tests for specific fields. A phone number one way, an email another. Error checking always depends on what data you are receiving and what you plan on doing with it. Also on the possible vulnerabilities of any given action.
For example an upload field would need more rigorous checks to prevent malicious code being unserted onto your server.