Link to home
Start Free TrialLog in
Avatar of Robert Granlund
Robert GranlundFlag for United States of America

asked on

PHP PDO Sanatize user input

What is the best way to sanitize user input?
	// Check for a State:
	if (empty($_POST['state'])) {
		$errors[] = 'You forgot to enter a state.';
	} else {
		$st = mysql_real_escape_string($_POST['state']);
	}

Open in new window


?????
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Oh, nevermind - now I get it.

The mantra is "accept only known good values."  This should obviously not be restated as "exclude all known bad values" because there are more bad values than you can think of, and if you approach security from the wrong end of the gun, well, it will not end in a way you enjoy.

All external data must be considered tainted and treated as an attack vector.

The escape_string() are used to make the data safe for use in a query string.  But that really does nothing to sanitize the input.  You would still want to check the basics.  For example, if your script is going to rely on a state abbreviation, one obvious check would be to see that the input was a string, two characters in length, and that it matched one of the standard state abbreviations.  If you expect a person's name, you might have a regular expression that kept only the letters of the alphabet, along with the comma, dot and hyphen.  Things like that are important.

On the outbound side, if your script echoes any browser output that was received from an external source, use htmlentities() or htmlspecialchars() to prevent your site from becoming an attack vector.
ASKER CERTIFIED SOLUTION
Avatar of Gary
Gary
Flag of Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
@rgranlund, I'm concerned that you're missing the point here.  PDO does not sanitize input.  Your own PHP script must sanitize the input.  There is a big difference between making a query string that can work correctly and having the right data in the data base after the query has been run.

PHP has functions that we use to sanitize input.  This is what you should be looking at:
http://php.net/manual/en/book.filter.php

And I really urge you to take a moment and read the article linked above.  It will answer your questions about how to use the various MySQL extensions.  The reason I wrote it is because I grew weary of answering this sort of question over and over -- it's such a common question, and so commonly misunderstood, that it needed to be explained in some detail.  The article does that, with tested and working code samples showing, in parallel construction, exactly how to work with MySQL, MySQLi, PDO, and MySQLi with prepared statements.