page } //we create an object of a fictional class Page, which is now //moderately protected from evil user input $obj = new Page; $content = $obj->fetchPage($pid); //and now we have a bunch of PHP that displays the page ?>
需 要做的只是使用 strlen() 检查变量的长度是否非零;如果是,就使用一个全数字正则表达式来确保数据元素是有效的。如果 PID 包含字母、斜线、点号或任何与十六进制相似的内容,那么这个例程捕获它并将页面从用户活动中屏蔽。如果看一下 Page 类幕后的情况,就会看到有安全意识的 PHP 开发人员已经对用户输入 $pid 进行了转义,从而保护了 fetchPage() 方法,如下所示: 清单 11. 对 fetchPage() 方法进行转义 复制代码 代码如下: <?php class Page{ function fetchPage($pid){ $sql = “select pid,title,desc,kw,content,status from page where pid=''”.mysql_real_escape_string($pid).”''”; } } ?>
GET[''pid'']; if (strlen($pid)){ if (!ereg(”^[0-9]+$”,$pid) && strlen($pid) > 5){ //do something appropriate, like maybe logging them out or sending them back to home page } } else { //empty $pid, so send them back to the home page } //we create an object of a fictional class Page, which is now //even more protected from evil user input $obj = new Page; $content = $obj->fetchPage($pid); //and now we have a bunch of PHP that displays the page ?>