13

I am a beginner PHP developer who was working with an issue regarding PHP script injection.
Fortunately PHP has functions like filter_var and strip_tags which did the job perfectly for me. But I don't understand the difference between the terms Sanitize and Validate
Please explain me the difference, Thanks

  • 3
    Perhaps think of it this way: Validation would be for rules (e.g. form requirements - password cannot be left empty) while Sanitize would be protection against malicious content. – Chris Burton Sep 15 '15 at 04:58
  • 1
    the definition listed under both those tags you added is as god as any –  Sep 15 '15 at 04:59
  • @dagon but the clean code means it is clean from malicious characters which avoids injection right? –  Sep 15 '15 at 05:06
  • "clean" for what purpose? adding to db, adding to web page, sending in email , theses are all different –  Sep 15 '15 at 05:09
  • 1
    I guess Chris's explanation gives me a new point of view to think, Thanks chris –  Sep 15 '15 at 05:13

2 Answers2

16

To validate is to make sure that the input matches your business rules. If it doesn't, you reject the input. You could be expecting user to provide you a number but if you receive something that's not a number, then that's a validation error.

Whereas sanitizing means to ensure that the format of the input doesn't break its container. This could be a semicolon(;) mistakenly added to the input by the user so you remove/escape it for him when it gets sent to you. Sanitization is also used to escape any attempt to cause data corruption when dealing with database based on user input.

Ali Idrees
  • 578
  • 2
  • 12
  • When you write "business rules". are you talking about the logic in the controller? (MVC model; in this case the control structures like if-else if-else, switch)) – carloswm85 May 18 '21 at 15:51
1

Sanitize remove all illegal characters from the variable say $email, if you use filter_var with validate param then it check if it is a valid email address or not.

$a = 'joe@example.org';

$sanitized_a = filter_var($a, FILTER_SANITIZE_EMAIL);
if (filter_var($sanitized_a, FILTER_VALIDATE_EMAIL)) {
    echo "This (a) sanitized email address is considered valid.\n";
}

See this link also for your reference.

Ashish Ranade
  • 595
  • 2
  • 14