Making my form secure

Discussion in 'PHP' started by Venlo, Jun 28, 2012.

  1. #1
    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):
     
    Venlo, Jun 28, 2012 IP
  2. NetStar

    NetStar Notable Member

    Messages:
    2,471
    Likes Received:
    541
    Best Answers:
    21
    Trophy Points:
    245
    #2
    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:
     
    NetStar, Jun 28, 2012 IP