PHP-strlen($string)不合作 Terraria服务器列表 添加服务器! 标题: IP和端口:(例如:127.0.0.1:7777) 说明: 电子邮件: 类型:HamachiNon Hamachi

PHP-strlen($string)不合作 Terraria服务器列表 添加服务器! 标题: IP和端口:(例如:127.0.0.1:7777) 说明: 电子邮件: 类型:HamachiNon Hamachi,php,mysql,string,strlen,Php,Mysql,String,Strlen,您最好在PHP中使用empty()函数,该函数检查变量是否为空(如strlen(…)==0) 还有:不要忘记变量的mysql\u real\u escape\u string() 为什么不直接使用if(!$somestring).?空字符串将测试为false,空字符串也将测试为null——只要$somestring不能设置为正常工作的非字符串值(除了null)。例如: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN

您最好在PHP中使用
empty()
函数,该函数检查变量是否为空(如
strlen(…)==0


还有:不要忘记变量的
mysql\u real\u escape\u string()

为什么不直接使用
if(!$somestring).
?空字符串将测试为
false
,空字符串也将测试为
null
——只要
$somestring
不能设置为正常工作的非字符串值(除了
null
)。例如:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" href="StylesTSL.css" type="text/css" media="screen">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Terraria Server List</title>
</head>
<body>
<div id="page">
<div id="logobase">
<div class="filler"></div>
<center><img src="logo.png" width="400" height="100"/></center>
</div>
<div class="filler"></div>
<div id="form">
<center>
<h1>Add a server!</h1>
<form action="" method="post">
Title: <input type="text" name="title" /><br />
IP & Port: <input type="text" name="ip" />(E.G: 127.0.0.1:7777)<br />
Description:<br />
<textarea name="desc"></textarea><br />
E-Mail: <input type="text" name="email" /><br />
Type:       <select name='type'><option value="Hamachi" selected>Hamachi</option><option value="Non-Hamachi">Non-Hamachi</option></select><br />
<input type="submit" name="submit" value="Submit server!" />
</form>
</center>
</div>
<div class="filler"></div>
<?php
//Our variables
$title = $_POST['title'];
$ip = $_POST['ip'];
$desc = $_POST['desc'];
$type = $_POST['type'];
$email = $_POST['email'];
$submit = $_POST['submit'];
//Connect to our DB
$con = mysql_connect("localhost", "x", "x");   
mysql_select_db("bobrocke_users", $con) or die("Could not select database");
if ($submit) {
    if (strlen($title) == 0) {
        die("Invalid title!");
    }
    else if (strlen($title) >= 51) {
        die("Invalid title!");
    }
    else if (strlen($ip) == 0) {
        die("Invalid IP!");
    }
    else if (strlen($ip) >= 51) {
        die("Invalid IP!");
    }
    else if (strlen($desc) == 0) {
        die("Invalid description!");
    }
    else if (strlen($email) == 0) {
        die("Invalid E-Mail!");
    }
    else if (strlen($email) >= 101) {
        die("Invalid E-Mail!");
    }
    else {
    mysql_query("INSERT INTO `Servers` (`ip`, `desc`, `type`, `title`, `email`) VALUES('".$ip."', '".$desc."', '".$type."', '".$title."', '".$email."')") or die(mysql_error()); 
    }
}
$get_all = mysql_query("SELECT * FROM Servers");
while ($row = mysql_fetch_assoc($get_all)) {
?>
<div class="servbox">
<center>
<h1><?php echo $row['title']?></h1><br /></center>
IP: <span class="ip"><?php echo $row['ip']?></span><br /><hr />
<p><?php echo $row['desc']?></p><br /><br />
<a href="http://bobcraft-games.com/TSL/page.php?id=<?php echo $row['id'] ?>">Server's Page</a><br />
Type: <?php echo $row['type']?><br /><br />
</div>
<div class="filler"></div>
<?php
}
?>
</div>
</body>
</html>
这还将捕获表单数据中未提交
$title
的情况

在查询中使用字符串时,还应转义字符串。因此:

...
    if (!$title) {
        die("Invalid title!");
    }
    else if (strlen($title) >= 51) {
        die("Invalid title!");
    }
...
……应成为:

mysql_query("INSERT INTO `Servers` (`ip`, `desc`, `type`, `title`, `email`) VALUES('".$ip."', '".$desc."', '".$type."', '".$title."', '".$email."')") or die(mysql_error()); 
否则,人们可能会将SQL重要字符和代码放入表单数据中,从而干扰您的查询

使用trim()可以消除字符串开头和结尾的所有空格。使用空(修剪($var))进行检查

由于要使用mb_strlen()计算字符数时使用的是utf-8,因此strlen()不起作用。 如果某些代码不起作用,我将执行以下操作:

  • 隔离问题。摆脱一切不相关的东西
  • 试着通过问自己“我的主张和期望是什么?”来澄清它应该做什么
  • 编写一个特定的脚本来测试行为不端的代码
  • 修改行为不端的代码,直到其行为符合预期(如果需要,使其更易于测试)

隔离问题。摆脱一切不相关的东西。 首先,让我们带上你的想法,摆脱一切与手头的具体问题无关的东西。离开这个世界,就是离开这个世界。所以,我们现在可以看得更清楚

然后,试着通过问“我的主张和期望是什么?”来澄清它应该做什么。 我从你的代码中猜测:

  • 给定
    • 信息字段(标题、名称、ip)
    • 以及它的最小长度
    • 以及它的最大长度
  • 由长度小于最小长度或大于其最大长度的用户提交值时
    • 然后,应拒绝该值
  • 否则就可以了
编写一个特定的脚本来测试行为不端的代码 我将创建一个html/php脚本,纯粹是为了测试导致悲伤的php。例如,将其命名为
FormFieldValidatorTest.php
。测试脚本与web站点项目放在一起,但仅由我运行。所以,我会把它放在一个密码保护的目录或其他公众无法访问的地方

我想要一个UTF-8 html页面,提交一些已知长度的字符串。比如,我们知道的字母“a”只有一个字符长,而我们知道的“空白字段”只有零个字符长

mysql_query("INSERT INTO `Servers` (`ip`, `desc`, `type`, `title`, `email`) VALUES('".
  mysql_real_escape_string($ip)."', '".
  mysql_real_escape_string($desc)."', '".
  mysql_real_escape_string($type)."', '".
  mysql_real_escape_string($title)."', '".
  mysql_real_escape_string($email)."')")
or die(mysql_error()); 
我想在
FormFieldValidatorTest.php
的html部分添加一些php。如果运行了结果(即,
$testResultsArray
null
不相同),则应打印结果:

最后,我充实了
assertTrue()
函数。这基本上是测试第一个参数是否未通过断言测试。然后将该结果和
消息作为记录附加到
$testResultsArray

/**
* @desc A TRUE assertion
* @param mixed - a value that we expect to be true
* @param string - a message to help understand what we are testing
* @param array - a collection of results so far passed by reference
* @return void
*/
function assertTrue( $value, $message, &$testResultsArray ) {   

    if ( $value ) {
        //value is as asserted
        $currentResult = array(         
            'message' => $message,
            'hasFailed' => FALSE
            );
    } else {
        //value is not as asserted
        $currentResult = array(
            'message' => $message,
            'hasFailed' => TRUE
            );
    }   

    $testResultsArray[] = $currentResult;   

}
现在,测试脚本已经完成

如果我运行它,并看到它通过,我可以肯定斯特伦是合作的。如果失败,我可以继续:

修改行为不端的代码,直到其行为符合预期。 为了做到这一点,您可能需要能够将行为不端的位拆分为一个单独的函数或类,该函数或类位于它自己的文件中。这使得它可以重用,因此可以从测试代码和实时生产代码中调用它

我们真正应该测试的是长度规则,它规定只允许特定长度的字符串

所以,让我们把它分离出来,这样我们就可以测试它了。可能是名为
ServerValidationRules.php

<?php 
//ServerValidationRules.php

/**
* @desc boolean function to test string length 
* @param string to test
* @param integer defining minimum length required
* @param integer defining maximum length required
* @return TRUE if its the correct length, FALSE otherwise.
*/
function isCorrectLength( $string, $minLength, $maxLength ) {

    if ( strlen( $string ) < $minLength ) {
        //its too short
        return FALSE;
    }

    if ( strlen( $string ) > $maxLength ) {
        //its too long
        return FALSE;
    }
    return TRUE;
}
因此,我们现在可以将生产脚本中的代码替换为:

<title>Terraria Server List</title>
...
<?php
...
if ( $submit ) {    
    if (!( isCorrectLength( $title, 0, 50 ) )) {
        die("Invalid title!");
    }    
    elseif (!( isCorrectLength($ip, 0, 50) )) {
        die("Invalid IP!");
    }
    elseif (!( isCorrectLength( $desc, 0, 10000 ) )) {
        die("Invalid description!");
    }    
    elseif (!( isCorrectLength( $email, 0, 100 ) )) {
        die("Invalid E-Mail!");
    }
    else {
        //do the insert
    }
}
...
然后在测试脚本中向测试套件函数添加更多断言

...

/**
* @desc A suite of tests to excercise that troublesome code
* @return array of results for each test done
*/
function runTestSuite() {

    /**
    * Initialize the results array
    */
    $testResultsArray = array();

    ...

    /**
    * Test some variants of possible user submitted data
    * 
    * @todo We ought to invoke an assertFalse() function.
    *  In meantime, hack it by passing a negated value to assertTrue().
    */

    /**
    * When given values that are too long, 
    * expect a validation failure.
    */
    $validationMessages = array();
    $result = isServerFieldsValid(
            array(
                'title' => str_repeat( 'a' , 51 ),
                'ip' => str_repeat( 'a' , 51 ),
                'desc' => str_repeat( 'a' , 1001 ),
                //?'type' => str_repeat( 'a' , 1001 ),
                'email' => str_repeat( 'a' , 101 ),
                ),
            $validationMessages
            );

    assertTrue(                 
        (!( $result )), 
        'Expect it to be TRUE that result is False when given long values',
        $testResultsArray );

    assertTrue(                 
        in_array( 'Invalid title!', $validationMessages ), 
        'Expect messages to say "Invalid title!"', 
        $testResultsArray );

    assertTrue(                 
        in_array( 'Invalid IP!', $validationMessages ), 
        'Expect messages to say "Invalid IP!"', 
        $testResultsArray );

    assertTrue(                 
        in_array( 'Invalid description!', $validationMessages ), 
        'Expect messages to say "Invalid description!"', 
        $testResultsArray );

    assertTrue(                 
        in_array( 'Invalid E-Mail!', $validationMessages ), 
        'Expect messages to say "Invalid E-Mail!"', 
        $testResultsArray );

    /**
    * When given values that are too short,
    *  expect a validation failure.
    */
    $validationMessages = array();
    $result = isServerFieldsValid(
            array(
                'title' => null,
                'ip' => null,
                'desc' => null,             
                'email' => null,
                ),
            $validationMessages
            );

    assertTrue(                 
        (!( $result )), 
        'Expect it to be TRUE that result is False when given short values',
        $testResultsArray );

    assertTrue(                 
        in_array( 'Invalid title!', $validationMessages ), 
        'Expect messages to say "Invalid title!"', 
        $testResultsArray );

    assertTrue(                 
        in_array( 'Invalid IP!', $validationMessages ), 
        'Expect messages to say "Invalid IP!"', 
        $testResultsArray );

    assertTrue(                 
        in_array( 'Invalid description!', $validationMessages ), 
        'Expect messages to say "Invalid description!"', 
        $testResultsArray );

    assertTrue(                 
        in_array( 'Invalid E-Mail!', $validationMessages ), 
        'Expect messages to say "Invalid E-Mail!"', 
        $testResultsArray );

    /**
    * When given values that are the correct length,
    *  expect a validation success.
    */
    $validationMessages = array();
    $result = isServerFieldsValid(
            array(
                'title' => 'a title',
                'ip' => 'an ip',
                'desc' => 'a desc',             
                'email' => 'an email',
                ),
            $validationMessages
            );

    assertTrue(                 
        ( $result ), 
        'Expect it to be TRUE that result is True when given correct values',
        $testResultsArray );

    assertTrue(                 
        (!( in_array( 'Invalid title!', $validationMessages ) )), 
        'Expect messages NOT to say "Invalid title!"', 
        $testResultsArray );

    assertTrue(                 
        (!( in_array( 'Invalid IP!', $validationMessages ) )), 
        'Expect messages NOT to say "Invalid IP!"', 
        $testResultsArray );

    assertTrue(                 
        (!( in_array( 'Invalid description!', $validationMessages ) )), 
        'Expect messages NOT to say "Invalid description!"', 
        $testResultsArray );

    assertTrue(                 
        (!( in_array( 'Invalid E-Mail!', $validationMessages ) )), 
        'Expect messages NOT to say "Invalid E-Mail!"', 
        $testResultsArray );


    return $testResultsArray;
}

...
所以,完整的测试脚本

因此,如果通过,我们可以通过调用新的、经过良好测试的isServerFieldsValid()函数替换所有那些
if(strlen){die}
语句来修改生产代码:

<title>Terraria Server List</title>

...

if ( $submit ) {
    $messages = array();
    if (!( isServerFieldsValid( $_POST, $messages ) )) {
        echo 'Invalid data was submitted:' . PHP_EOL;

        foreach( $messages as $message ) {
            echo $message . PHP_EOL;
        }

        exit;
    } else {
        //do the insert
} 
...
Terraria服务器列表
...
如果($提交){
$messages=array();
如果(!(isServerFieldsValid($\u POST,$messages))){
echo“提交了无效数据:”。PHP_EOL;
foreach($messages作为$message){
echo$message.PHP\u EOL;
}
出口
}否则{
//插入
} 
...

好吧,这就是我如何处理那些不合作的代码

代码:

  • 测试套件-
  • 验证功能-
  • 修改表格页-
注: 我花了几个小时来写这个答案,但写实际测试的时间却很少。一旦你养成了这个习惯,通常只需要几分钟就可以写出一个测试,并找出为什么一些代码不合作

提示:您不需要编写自己的断言函数。
请参阅:

echo$title before并显示结果。您是否将“blank”定义为包含空格字符?您可能需要
trim
字符串…在此行之前执行
var_dump($submittedValue);
以及echo strlen($title)并在此处显示。(或者更好的是,尝试一些常见的PHP测试方法,比如回显数据,然后找出实际问题所在并重新发布问题。)抱歉,我弄错了。我收到了很多垃圾邮件
<?php 
//ServerValidationRules.php

/**
* @desc boolean function to test string length 
* @param string to test
* @param integer defining minimum length required
* @param integer defining maximum length required
* @return TRUE if its the correct length, FALSE otherwise.
*/
function isCorrectLength( $string, $minLength, $maxLength ) {

    if ( strlen( $string ) < $minLength ) {
        //its too short
        return FALSE;
    }

    if ( strlen( $string ) > $maxLength ) {
        //its too long
        return FALSE;
    }
    return TRUE;
}
<?php
//FormFieldValidatorTest.php

require_once('ServerValidationRules.php');

...

/**
* @desc A suite of tests to excercise that troublesome code
* @return array of results for each test done
*/
function runTestSuite() {


    $testResultsArray = array();

    /**
    * Test some known data submitted via a form parameter 
    */
    assertTrue( 
        //( strlen( $_REQUEST['singleCharacterString'] ) == 1 ), 
        isCorrectLength( $_REQUEST['singleCharacterString'], 0, 1 ),
        'Expect it to be TRUE that singleCharacterString http parameter
        has a stringlength of 1', 
        $testResultsArray );

    /**
    * @todo Add more tests here. 
    */
    assertTrue( 
        //( strlen( $_REQUEST['emptyString'] ) == 0 ), 
        isCorrectLength( $_REQUEST['emptyString'], 0, 0 ),
        'Expect it to be TRUE that emptyString http parameter
        has a stringlength of 0', 
        $testResultsArray );

    return $testResultsArray;
}
...
<title>Terraria Server List</title>
...
<?php
...
if ( $submit ) {    
    if (!( isCorrectLength( $title, 0, 50 ) )) {
        die("Invalid title!");
    }    
    elseif (!( isCorrectLength($ip, 0, 50) )) {
        die("Invalid IP!");
    }
    elseif (!( isCorrectLength( $desc, 0, 10000 ) )) {
        die("Invalid description!");
    }    
    elseif (!( isCorrectLength( $email, 0, 100 ) )) {
        die("Invalid E-Mail!");
    }
    else {
        //do the insert
    }
}
...
<?php
//ServerValidationRules.php
...
/**
* @desc tests user-submitted fields appending feedback to an array of messages upon failure.
* @param associative array of Posted values keyed by field name
* @param array of messages passed by reference
* @return boolean True if all fields are valid. False otherwise.
*/
function isServerFieldsValid( $values, &$messages ) {   

    $hasFailed = FALSE;

    if (!( isCorrectLength( $values['title'], 1, 50 ) )) {
        $hasFailed = TRUE;
        $messages[] = "Invalid title!";
    }    

    if (!( isCorrectLength($values['ip'], 1, 50) )) {
        $hasFailed = TRUE;
        $messages[] = "Invalid IP!";    
    }

    if (!( isCorrectLength( $values['desc'], 1, 1000 ) )) {
        $hasFailed = TRUE;
        $messages[] = "Invalid description!";
    }    

    if (!( isCorrectLength( $values['email'], 1, 100 ) )) {
        $hasFailed = TRUE;
        $messages[] = "Invalid E-Mail!";
    }

    if ( $hasFailed ) {
        return FALSE;
    } 
    //else
    return TRUE;
}
...

/**
* @desc A suite of tests to excercise that troublesome code
* @return array of results for each test done
*/
function runTestSuite() {

    /**
    * Initialize the results array
    */
    $testResultsArray = array();

    ...

    /**
    * Test some variants of possible user submitted data
    * 
    * @todo We ought to invoke an assertFalse() function.
    *  In meantime, hack it by passing a negated value to assertTrue().
    */

    /**
    * When given values that are too long, 
    * expect a validation failure.
    */
    $validationMessages = array();
    $result = isServerFieldsValid(
            array(
                'title' => str_repeat( 'a' , 51 ),
                'ip' => str_repeat( 'a' , 51 ),
                'desc' => str_repeat( 'a' , 1001 ),
                //?'type' => str_repeat( 'a' , 1001 ),
                'email' => str_repeat( 'a' , 101 ),
                ),
            $validationMessages
            );

    assertTrue(                 
        (!( $result )), 
        'Expect it to be TRUE that result is False when given long values',
        $testResultsArray );

    assertTrue(                 
        in_array( 'Invalid title!', $validationMessages ), 
        'Expect messages to say "Invalid title!"', 
        $testResultsArray );

    assertTrue(                 
        in_array( 'Invalid IP!', $validationMessages ), 
        'Expect messages to say "Invalid IP!"', 
        $testResultsArray );

    assertTrue(                 
        in_array( 'Invalid description!', $validationMessages ), 
        'Expect messages to say "Invalid description!"', 
        $testResultsArray );

    assertTrue(                 
        in_array( 'Invalid E-Mail!', $validationMessages ), 
        'Expect messages to say "Invalid E-Mail!"', 
        $testResultsArray );

    /**
    * When given values that are too short,
    *  expect a validation failure.
    */
    $validationMessages = array();
    $result = isServerFieldsValid(
            array(
                'title' => null,
                'ip' => null,
                'desc' => null,             
                'email' => null,
                ),
            $validationMessages
            );

    assertTrue(                 
        (!( $result )), 
        'Expect it to be TRUE that result is False when given short values',
        $testResultsArray );

    assertTrue(                 
        in_array( 'Invalid title!', $validationMessages ), 
        'Expect messages to say "Invalid title!"', 
        $testResultsArray );

    assertTrue(                 
        in_array( 'Invalid IP!', $validationMessages ), 
        'Expect messages to say "Invalid IP!"', 
        $testResultsArray );

    assertTrue(                 
        in_array( 'Invalid description!', $validationMessages ), 
        'Expect messages to say "Invalid description!"', 
        $testResultsArray );

    assertTrue(                 
        in_array( 'Invalid E-Mail!', $validationMessages ), 
        'Expect messages to say "Invalid E-Mail!"', 
        $testResultsArray );

    /**
    * When given values that are the correct length,
    *  expect a validation success.
    */
    $validationMessages = array();
    $result = isServerFieldsValid(
            array(
                'title' => 'a title',
                'ip' => 'an ip',
                'desc' => 'a desc',             
                'email' => 'an email',
                ),
            $validationMessages
            );

    assertTrue(                 
        ( $result ), 
        'Expect it to be TRUE that result is True when given correct values',
        $testResultsArray );

    assertTrue(                 
        (!( in_array( 'Invalid title!', $validationMessages ) )), 
        'Expect messages NOT to say "Invalid title!"', 
        $testResultsArray );

    assertTrue(                 
        (!( in_array( 'Invalid IP!', $validationMessages ) )), 
        'Expect messages NOT to say "Invalid IP!"', 
        $testResultsArray );

    assertTrue(                 
        (!( in_array( 'Invalid description!', $validationMessages ) )), 
        'Expect messages NOT to say "Invalid description!"', 
        $testResultsArray );

    assertTrue(                 
        (!( in_array( 'Invalid E-Mail!', $validationMessages ) )), 
        'Expect messages NOT to say "Invalid E-Mail!"', 
        $testResultsArray );


    return $testResultsArray;
}

...
<title>Terraria Server List</title>

...

if ( $submit ) {
    $messages = array();
    if (!( isServerFieldsValid( $_POST, $messages ) )) {
        echo 'Invalid data was submitted:' . PHP_EOL;

        foreach( $messages as $message ) {
            echo $message . PHP_EOL;
        }

        exit;
    } else {
        //do the insert
} 
...