PHP - strlen($ string)不合作

时间:2012-02-03 20:25:42

标签: php mysql string strlen

<!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>

好吧,我要做的是限制用户发布无效的空白字段。

无论出于何种原因,这些措施if (strlen($submittedValue) == 0)或其他。

4 个答案:

答案 0 :(得分:2)

你最好在PHP中使用empty()函数来检查变量是否为空(如strlen(...) == 0

并且:不要忘记mysql_real_escape_string()变量!

答案 1 :(得分:1)

使用trim()消除字符串开头和结尾的任何空格。使用空(trim($ var))来检查。

由于您在使用utf-8时想要计算字符数,请使用mb_strlen()http://php.net/manual/en/function.mb-strlen.php

答案 2 :(得分:0)

为什么不简单地使用if (!$somestring) ...?空字符串将测试为falsenull也是如此 - 只要$somestring无法设置为非字符串值(null除外),应该工作正常。例如:

...
    if (!$title) {
        die("Invalid title!");
    }
    else if (strlen($title) >= 51) {
        die("Invalid title!");
    }
...

这也将捕获表单数据中未提交$title的情况。

在查询中使用它们时,也应该转义字符串。所以:

mysql_query("INSERT INTO `Servers` (`ip`, `desc`, `type`, `title`, `email`) VALUES('".$ip."', '".$desc."', '".$type."', '".$title."', '".$email."')") or die(mysql_error()); 

..应该成为:

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()); 

否则,人们可能会通过将SQL重要字符和代码放入表单数据来搞乱您的查询。

答案 3 :(得分:0)

因此,strlen()不合作。

如果某些代码没有合作,我会做以下事情:

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

隔离问题。通过摆脱一切不相关的东西。

首先,让我们拿走你的original example code并摆脱与手头的具体问题无关的一切。离开validation code that uses strlen。所以,我们现在可以更清楚地看到了。

然后,通过询问&#34;我的主张和期望是什么来尝试澄清它应该做什么?&#34;。

我想从你的代码中可以看出:

  • 给定
    • 信息的字段(标题,名称,IP)
    • 及其最小长度
    • 及其最大长度
  • 当用户提交的值长度小于最小长度或大于最大长度
    • 然后,该值应被拒绝
  • else 确定

编写一个特定的脚本来测试行为不端的代码

我创建一个html / php脚本纯粹是为了测试引起悲伤的php。例如,将其称为FormFieldValidatorTest.php。测试脚本与网站项目一起使用,但仅供我运行。因此,我将其放入受密码保护的目录或公众无法访问的其他位置。

我想要一个 UTF-8 html页面,提交一些已知长度的字符串。说,这封信&#39; a&#39;我们知道的是一个字符长,一个空字段&#39;我们知道它是零个字符。

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>My Test</title>
</head>
<body>

<form action="" method="get">
<input name="singleCharacterString" type="text" value="a" size="1" maxlength="1">
<input name="emptyString" type="text" value="" size="1" >
<input type="submit" name="Submit" value="Run Tests">
</form>
...

然后,在FormFieldValidatorTest.php的顶部,我写了一些PHP代码:

  • 接收那些固定的,硬编码的表格值(夹具数据)。
  • 将灯具数据传递给某些测试,然后
  • 给我一系列结果

为了保持清洁,我将测试代码的内容放入一个函数中,称之为runTestSuite(),它将在下面充实。

<?php 
//FormFieldValidatorTest.php

if ( $_REQUEST['Submit'] == 'Run Tests' ) {

    //perform the tests
    $testResultsArray = runTestSuite();

    /**
    * Lets loop through the results and count the failures
    */
    $failureCounter = 0;
    foreach ( $testResultsArray as $result ) {
        if ( $result['hasFailed'] ) {
            $failureCounter++;
        }   
    }
} else {
    //no tests were run set the results to null
    $testResultsArray = null;
}

?>
<html>
...

我在FormFieldValidatorTest.php的html部分添加了一些php。这应该打印出结果(如果$testResultsArraynull不同):

<?php
//FormFieldValidatorTest.php
...
?>
<html>
...
<body>
<form action="" method="get">
...
</form>

<?php if ( $testResultsArray !== null ) : ?>
    <h1>Results</h1>
    <pre>
    <?php if ( $failureCounter > 0 ) : ?>
        Failed. <?php echo $failureCounter ?> tests failed.
        <?php print_r( $testResultsArray ); ?>
    <?php else : ?>
        Passed
    <?php endif; ?>
    </pre>
<?php endif; ?>
</body>
</html>

然后,我填写了runTestSuite()函数的内容。这基本上是对assertTrue()函数的两次调用,我将在后面充实。

  • 首先,它断言在给定1时strlen返回singleCharacterString是真的。
  • 然后,它断言当给定0时strlen返回emptyString是真的。

同时传递描述每个测试的消息。这些存储在结果数组中,以便在测试失败时帮助调试。


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

    /**
    * Lets Run some tests
    */

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

    /**
    * Test some known data submitted via a form parameter 
    */
    assertTrue( 
        ( strlen( $_REQUEST['singleCharacterString'] ) == 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 ), 
        'Expect it to be TRUE that emptyString http parameter
        has a stringlength of 0', 
        $testResultsArray );

    return $testResultsArray;
}

最后,我充实了assertTrue()功能。这基本上测试了第一个参数是否已失败断言测试。然后,它会将结果和message作为$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;   

}

现在测试脚本已完成。 See it here

如果我运行它并看到它通过,我可以确定strlen是合作的。如果它失败了我可以继续:

修改行为不当的代码,直到它按预期运行。

为了做到这一点,你可能需要能够将行为不当的位分成一个单独的函数或类,它位于自己的文件中。这使得可重用,因此可以从测试代码和实时生产代码中调用它。

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

所以,让我们隔离一下,这样我们就可以测试它了。可能是名为ServerValidationRules.php

的文件中名为isCorrectLength()的 rules 库中的函数
<?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;
}

然后我们可以替换测试中的代码,而不是使用原生的strlen()函数。

<?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
    }
}
...

或者,更好的是,将 length 规则移动到单个函数中,以便逻辑可以被其他代码重复使用(即测试套件中的某些代码)。

我们可以将所有这些内容包装到一个名为isServerFieldsValid的函数中,并将其放入我们的ServerValidationRules.php文件中。

<?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;
}

...

所以,完整的测试脚本now looks like this

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

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

嗯,这就是我如何处理不合作的代码。

代码:

注意:

我花了几个小时来写这个答案,但很少有时间来编写实际测试。一旦养成习惯,通常只需几分钟就可以完成测试,并找出为什么有些代码没有合作。

提示:您不需要编写自己的断言函数。 请参阅:http://www.simpletest.org/en/start-testing.html

相关问题