Shiv Deepak
Shiv Deepak

Reputation: 3116

Safety precautions while doing html form processing using javascript, PHP, MySQL

I am not a professional web developer but I love web development as a hobby.. I am a student and I was asked to make a departmental event web site. I need to create HTML forms for user registration. I am aware of XSS Scripting attack and SQL Injection. But don't know how they exactly work. I am using PHP and MySQL on server side.

I am taking in consideration:

All this I am doing using RegEx check - both with javascript and PHP

Now my questions are:

I don't want to restrict users from inputting symbols which are harmless. So is there any particular set of character which I need to filter before storing the values into the database, so I can properly write regex checks for my form fields?

I have searched in google but was not able to find a proper answer. :(

Upvotes: 1

Views: 839

Answers (2)

Robus
Robus

Reputation: 8269

As for usename, this should do the job:

if (preg_match('/^[a-z\d_\-<>]{5,20}$/i', $username)) {
    echo "Your username is ok."; 
    // Note that you still have to do something with <>
    // Though, personally I'd advise sticking to /^[a-z\d_]{5,20}$/i
} else {
    echo "Wrong username format.";
}

Source

As for SQL injection, use mysql_real_escape_string or mysqli_real_escape_string on everything you enter into the DB

Upvotes: 0

Borealid
Borealid

Reputation: 98509

To prevent SQL injection, you should use the language's escape function. For PHP, that's mysql_real_escape_string. Or, better yet, use PDO to restrict what users can put into the DB.

The HTML injection/XSS attack is different; you can store raw HTML in the database without issue, but before displaying any HTML originating with the user, call htmlspecialcharacters on it to prevent it from being interpreted by the client's web browser.

Do not code your own custom checks. You will miss something.

Upvotes: 1

Related Questions