phphtmlstrip-tags

My HTML Tags won't be stripped from $this->username


I am trying to strip my tags because someone keeps hacking my website by using the old ">blah as their username. For some reason my strip_tags() is not stripping the tags, but the addslashes() is working.

I don't know if I left off a bracket - but here is the code:

     public function register() {
    $correct = false;
        try {
            $con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
            $con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
            $this->username = strip_tags($this->username);
            $this->username = addslashes($this->username);
            $sql = "INSERT INTO User_Agents(username, password) VALUES(:username, :password)";

            $stmt = $con->prepare( $sql );
            $stmt->bindValue( "username", $this->username, PDO::PARAM_STR );
            $stmt->bindValue( "password", hash("sha256", $this->password . $this->salt), PDO::PARAM_STR );
            $stmt->execute();
            return "Registration Successful <br/> <a href='index.php'>Login Now</a>";
        }catch( PDOException $e ) {
            return $e->getMessage();
        }
 }

This is what it turns out to when it goes into my database:

Picture of what it entered


Solution

  • Simply disallowing usernames that can lead to problems might be a more simple/efficient solution. For example a preg_match("/^[a-zA-Z0-9\._]+$/", $username) would allow you to reject usernames that contain other characters than letters, digits, dots, or underscores.