PHP strlen(str) not working

时光毁灭记忆、已成空白 提交于 2019-12-14 03:33:56

问题


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?


回答1:


You are not returning anything from safeString.

Apart from that, what safeString does is redundant (htmlentities is a superset of htmlspecialchars, 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

$msg = isset($_POST['msg']) ? $_POST['msg'] :'';
if ($msg == '')
    echo "<h1>Test failed</h1>";
else {
    echo "Received value: ".htmlspecialchars($msg);
}

You should also definitely specify the input's encoding (see third parameter of htmlspecialchars).



来源:https://stackoverflow.com/questions/11275883/php-strlenstr-not-working

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!