Home > Net >  Is PHP Contact Form without input validation safe if used with prepare statements?
Is PHP Contact Form without input validation safe if used with prepare statements?

Time:03-05

I have a contact-us form on my website and I am trying to not limit users on the characters that they use, since we would like to support multilingual names. We only check the length and the structure of the name/e-mail, etc.

I know that it could be dangerous if the variables would be inserted directly into the query statement, but I am using prepared statements, like below.

$stmt = $conn->prepare("INSERT INTO contact_us_form (id,available_id,user_id,foreName,surName,mail,message) VALUES (?,?,?,?,?,?,?)");
$stmt->bind_param("iiissss",$num,$availableID,$userID,$foreName,$surName,$mail,$message);    
$stmt->execute();
$stmt->close();
$conn->close();

Is this the proper way to save raw data in my mysql database? I would also send an e-mail to myself, but I would escape special characters before doing that.[UTF-8]

CodePudding user response:

Using prepared statements is good protection against SQL injection attacks. However that isn't sufficient to protect against other types of attacks. How else is this data going to be used?

If this message is ever shown in a web page (for example to the person who is going to read the message) it needs to be escaped with HTML entities.

If this message is ever sent as an email, characters like new lines that are not safe for email headers need to be stripped from the email address, name and other fields that are put into email headers.

Basically, any time you use this data anywhere, you need to make sure that it is treated as user-submitted, untrusted data. It will always need to be escaped or sanitized in a way that is appropriate for the particular context in which it is inserted.

CodePudding user response:

Input validation isn't really related to security, but it can be considered defense-in-depth. Input validation also prevents other vectors of abuse. For example, someone might submit 1GB of data to your contact form. Is this something that your application expects and can handle? Is your database column capable of storing this amount of data? If you don't validate the input, your application might crash. Reject invalid input.

Prepared statements prevent you from SQL injection if used correctly. You don't need to "sanitize" or do anything like that to the data. There are no "special characters" when using prepared statements. Your database also doesn't define any characters as specials; it will save whatever you give it. You must ensure though that you save the data in the correct character set and that you tell mysqli connection what that charset is.

And of course, when displaying the data in the HTML make sure that you format it properly so that your data doesn't break your HTML structure. Use htmlspecialchars() for that purpose.

  • Related