Sudhakar escribió:
a) the username should only begin either letters or numbers, and
Underscore character
example = user123, 123user, u_ser123, user_123 = completely case
insensitive
b) a user may choose not to have an underscore or numbers sometimes.
example = username
presently my validation for username is
$username = $_POST["username"];
if( $username == "" || !eregi("^[a-zA-Z0-9_]+$", $username) )
{
$error.="User name cannot be blank or has special characters";
}
You'd better get used to preg_* functions, their old ereg_* equivalent
will be deprecated in PHP 6. Not tested but...
if(
// Check non-empty, only valid chars and 1 to 16 chars
!preg_match('/^[a-z0-9_]{1,16}$/i', $username) ||
// Check at least one letter
!preg_match('/[a-z]/i', $username)
){
$error .= '......';
}
I've added an extra check. Replace 16 with your database field length.
Probably, it could all be done in only one expression but...
B) preventing sql injection
htmlentities
This is used to convert plain text into HTML, it has nothing to do with
SQL injection.
addslashes
This may help to avoid _some_ types of injection in some database
servers like MySQL, but it wouldn't help in Oracle or SQL Server.
trim
I won't even comment on this.
mysql-real-escape-string
This is a valid option for MySQL. Prepared statements are the other way.
magic_quotes_gp c is ON
The same as addslashes(), except that you'll get \'s inserted all around
your input and you'll have to remove it again when not using it for a
SQL query:
<p>Welcome, John O\'Hara!</p>
c) also with the prevention methods if a user types a special
character in the data will that character be written in the table as a
escaped character or how does it store those special characters
Why does it matter how the DBMS stores data internally?
d) a very important point here, i have a feature where a user can
check if a username is available or not. so while storing a username
if the username is stored as john\smith in mysql and if the user is
searching for johnsmith this would not match, so even in the table the
username should be stored without slashes as i have to read the
username and compare with what the user has typed to see if they both
are same or different.
You said users can only have letters, numbers and underscores... If you
also allow backslashes then of course "john\smith " is different to
"johnsmith" or "john_smith " or "john___smi th". My suggestion is that you
add an extra column to the table (possibly indexed) and check against it
as well:
Username StrippedUsernam e
============= =============== =
john_smith123 johnsmith
___123x___ x
$stripper_usern ame = strtolower(preg _replace('/[^a-z]+/', '', $username));
--
--
http://alvaro.es - Álvaro G. Vicario - Burgos, Spain
-- Mi sitio sobre programación web:
http://bits.demogracia.com
-- Mi web de humor al baño María:
http://www.demogracia.com
--