I am making a simple survey and I want to save the results to a MySQL database.
Could anyone let me know if this is the right order for validating and escaping things?
(mainly, the approach I am thinking is to only change the values right before using them in sql or outputting to browser)
in other words, is there a danger of PHP validation without slashes?
1) Receive $_POST values, stripping slashes if magic quotes is on
2) put POST values into variables
4) validate POST values.
3) stripslashes and htmlspecialchars just before output to screen
5) mysql_real_escape_string just befor entry into database.
I am nost sure if I should be escaping strings before validation. Here are the functions I use:
And here is my validation so far:PHP Code:// strips slashes if magic quotes on
function stripping($string){
if (!get_magic_quotes_gpc()){
return $string;
} else {
return stripslashes($string);
}
}
// prepares data to be output to page
function htmlsafe($string){
return htmlspecialchars($string);
}
}
// prepares data for database entry
function sqlsafe($string) {
$string=mysql_real_escape_string($string);
return $string;
}
And finally here is my sql that will be insertedPHP Code:// set variables
$title = stripping($_POST['title']);
$selection = stripping($_POST['selection']);
$other = stripping($_POST['other']);
// to check selection, and store error message
$array = ('selection1', 'selection2', 'selection3');
$err_message = '';
if (!strlen($title) > 0) {
$title = FALSE;
$err_message .= 'A title was not submitted. Please enter a title.<br />';
}
if (!in_array($selection, $array) {
$title = FALSE;
$err_message .= 'A valid selection was not made. Please make a selection.<br />';
}
if ($other == 'badword') {
$other = FALSE;
$err_message .= 'You cannot use the word ' . htmlsafe($badword) . 'Please submit another word.<br />';
if ($err_message > 0){
echo $err_message;
} else {
echo 'Success!';
// continue to SQL insert
}
PHP Code:$title = sqlsafe($title);
$selection = sqlsafe($selection);
$other = sqlsafe($other);
$sql = "INSERT INTO `tablename` (`col1`, `col2` , `col3` , `col4`) VALUES (NULL , `$title`, `$selection`, `$other`)";

