There are basically two ways of handling user input:
Sanitizing: This removes unwanted stuff from the input. The unwanted stuff may be various tags, invalidly formatted characters, certain words or letters, etc. This is almost always something you should do. The only exception is if the input is a simple value such as an integer or a boolean value, which can be handled directly with validating.
Validating: This makes sure that the input is indeed what you expect it to be. Is it a number, boolean value, text blocks, etc.? This is not so much about security as it is about actually getting the right kind of data for your program to be able to function.
For both of these points there is a PHP extension called Filter. It was made with this stuff in mind.
For sanitizing input you could do something like this:
$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
$age = filter_input(INPUT_POST, 'age', FILTER_SANITIZE_NUMBER_INT);
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
$password = filter_input(INPUT_POST, 'password', FILTER_UNSAFE_RAW);
And for validating:
if (preg_match('/[\w\d]{4,20}/', $name) === 0) {
die('Invalid name!');
}
if ( ! ctype_digit($age) || ($age < 13)) {
die('Invalid age or too young!');
}
if ( ! filter_var($email, FILTER_VALIDATE_EMAIL)) {
die('Invalid email address!');
}
if (strlen($password) < 10) {
die('Password is too short!');
}
One very important thing to remember is that there is no magic pill. User input cannot just be washed in bleach as it comes in, and then be said to be safe. You need to know what the user input should be and then treat it accordingly. If it is not what you know it should be then hit the brakes immediately and throw it back at the user.