PHP strlen(str)不起作用 [英] PHP strlen(str) not working

查看:288
本文介绍了PHP strlen(str)不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的网站上有一个表单,它接受来自文本区域的输入,如果它为空(strlen = 0),则另一种方式(如果文本中有文本)进行处理。
这里是表单的一部分:

 < form name ='contact'action ='contact.php'方法= 'POST' > 
...
留言*< 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>

现在PHP代码:

<$ p $ $ msg = isset($ _ POST ['msg'])?safeString($ _ POST ['msg']):'';
$ msg = substr($ msg,0,2048);
if(strlen($ msg)== 0)
echo< h1>测试失败< / h1>;
else {...}

以下是 safestring(str )方法:
$ b

 函数safeString($ str){
htmlentities($ str) ;
htmlspecialchars($ str);
}

每次我提交表格时,无论我放多少或多少在msg textarea中,它总是说它是空的(通过回显TEST FAILED)。另外,你是否知道我应该添加到我的 safestring()函数中来让我的表单更安全?

解决方案

您没有从 safeString 中返回


$ b $除此之外, safeString 是多余的( htmlentities htmlspecialchars ,后者的工作是防止XSS)。



最后,你应该真的不是 在接受输入时做这种消毒,但只有当你正在生产输出时。



换句话说,你的代码应该看起来更像

  $ msg = isset($ _ POST ['msg'])? $ _POST ['msg']:''; 
if($ msg =='')
echo< h1>测试失败< / h1>;
else {
echoReceived value:.htmlspecialchars($ msg);
}

您还应确定指定输入的编码请参阅 htmlspecialchars 的第三个参数)。


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 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).

这篇关于PHP strlen(str)不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆