Jump to content
Larry Ullman's Book Forums

Recommended Posts

I have a contact form on my site.  I'm using the book's methods to validate POST data from a textarea input field called "contact_info". 

 

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

...

if (empty($_POST['contact_info'])) {

     $contact_errors['contact_info'] = 'Please enter a comment.';

} elseif (preg_match('/^[A-Za-z0-9.,-$?!]*$/', $_POST['contact_info'])) {

     $_POST['contact_info'] = str_replace(' ','',$_POST['contact_info']); //remove all spaces

     $_POST['contact_info'] = trim($_POST['contact_info']); //remove any space before or after any characters

     $_POST['contact_info'] = escape_data($_POST['contact_info'], $dbc);

     // add htmlspecialchars ???

     // anything else ???

} else {

     $contact_errors['contact_info'] = 'Your comment contains inappropriate characters.  Allowable characters include letters a to z, letters A to Z, numbers 0 to 9, as well as, period, comma, exclamation mark, question mark, dollar sign and hyphen.';

}

...

}

 

<form method="post" accept-charset="utf-8">

...

<?php create_contact_form_input('contact_info', 'textarea', $contact_errors); ?>

...

</form>

 

 

 

What is the most secure way to validate user input from a textarea field?

 

Share this post


Link to post
Share on other sites

So sorry AGAIN for the delayed reply! This got lost on my end. It's important to differentiate between "validate" and "sanctify".  It's also important to think about how you want to handle invalid data. The most crucial step is to strip out any code, using strip_tags(), before the comments might be displayed on a web page. This will protect you from code injections but doesn't raise errors to the user. Which is fine, depending upon what you want to accomplish.

 

If you do want to validate the data and possibly show the error to the user, then a whitelist approach of what is a valid comment is probably not going to work as there are too many characters that could be valid. I'd go with a blacklist approach instead, knowing that there's not really a good reason for a comment to include , and those are dangerous. 

 

Regardless of whether you validate or not, though, you'll still need to strip tags from it and make sure it's safe to use in queries (using an escaping function or prepared statements).

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...