PHP Registration form

Associate
Joined
26 Jun 2003
Posts
1,140
Location
North West
I have a form with the fields:

username
password
password2
email

Is the best way to clean the user input this way? Or have a missed something?

PHP:
	foreach ($_POST as $value)
		$value = strip_tags(mysql_real_escape_string($value));
 
Nono! Bad idea! Do Not Do That!! (I haven't done it before, honest...)

Yo're effectively bypassing any register_globals settings, by doing exactly what register_globals does (mostly). Which is bad. You have no control over what variables will be created :)

One method is to setup an array containing all the variables you want, then loop through that. Or just do each one separately. Either way, I'd create a cleanVariable() function and pass each variable through it, to minimise code
duplication.

In terms of what to do...if you want an integer, you can simply use $var = intval($var) because, well, any malicious string wouldn't survive being converted to an integer.

If you want a string....if magic_quotes is on then you want to reverse its effects, since it's completely useless. You can do that with stripslashes():

Code:
if(magic_quotes_gpc()) stripslashes($var);
If your code is going into a database then you want to escape all the nasty characters with mysql_real_escape_string() (Note: you'll need an open database connection to do this - see the PHP manual)

As for strip_tags() - I'd use htmlentities()[/**] instead to be 100% sure that nothing malicious can be done since ALL HTML gets turned to meaningless text: For example these forums do it - I can type <b>Bold</b> and it'll be printed literally, not interpreted by browsers.

:)
 
Last edited:
PHP:
function strip_em(&$data) {
    if( is_array($data) )
        $data = strip_em($data);
    else
        $data = stripslashes($data);
}

strip_em($_POST);

Then mysql_real_escape_string before use in queries and htmlentities() before echoing. Sorted.
 
Back
Top Bottom