I have a form on my website that takes input from a text area and processes it one way if it is empty (strlen = 0) and another if it has text in it.
Here is part of the form:
<form name='contact' action='contact.php' method='post'>
...
Message*<br />
<textarea name='msg' rows='10' cols='70' maxlength='2048'><?php echo $msg ?></textarea><br />
...
<input type='submit' value='Send!' id='subby' name='fatk' style='height:60px; width:300px;' />
</form>
Now the PHP code:
$msg = isset($_POST['msg'])?safeString($_POST['msg']):'';
$msg = substr($msg,0,2048);
if (strlen($msg) == 0)
echo "<h1>Test failed</h1>";
else { ... }
Here’s the safestring(str) method:
function safeString($str) {
htmlentities($str);
htmlspecialchars($str);
}
Every time I submit the form, no matter how much or how little I put in the msg textarea, it always says it’s empty (by echoing TEST FAILED). Also, do you know anything else I should add to my safestring() function to make my forms more secure?
You are not returning anything from
safeString.Apart from that, what
safeStringdoes is redundant (htmlentitiesis a superset ofhtmlspecialchars, and the latter does the job of protecting against XSS).Finally, you should really not be doing this sanitization when accepting input but only when you are producing output.
Put toghether, your code should look more like
You should also definitely specify the input’s encoding (see third parameter of
htmlspecialchars).