I am trying to make a registration form which must be secure from SQL injection and XSS attacks. My script below strips out non alpha numeric characters from the username, then checks to see if its valid. Is this the best way of doing it? If you have any suggestions or improvements, please reply with them... function stripan ($string) { return preg_replace('/[^a-zA-Z0-9\s]/', '', $string); } if ($_POST['username']!="") { $username = stripan($_POST['username']); if ($username ="") { $errorcomment =. "No username was entered< br />"; $error = 1; } else { $errorcomment =. "No username was entered< br />"; $error = 1; } Code (markup):
I'm not sure who told you to do that but it's not right. You don't have to reinvent the wheel to avoid SQL Injection attacks.. Simply use PDO or mysqli with placeholders and prepared statements. Example: <?php // // Your database information // $dbname = "MySite"; $dbuser = "blah"; $dbpass = "pass123"; // // Connect to database // // Note: Should check to see if connected...but this is merely an example $db = new PDO("mysql:dbname=".$dbname.";host=localhost", $dbuser, $dbpass); $sql = "SELECT FirstName, LastName, Age FROM People WHERE LastName = :lastname;"; // :blah is the placeholder $sth = $db->prepare($sql); $sth->bindParam(":lastname", $_POST['lastname']); // Bind :lastname to user defined variable $sth->execute(); $sth->bindColumn('FirstName', $firstname); // Assign value of FirstName to $firstname $sth->bindColumn('LastName', $lastname); $sth->bindColumn('Age', $age); $sth->fetch(); print "I found $firstname who is $age years old\n"; ?> PHP: