三、 保护一个新的应用程序
如果你正在创建一个新的应用程序,那么,你可以从头开始创建一个安全抽象层。如今,PHP 5新改进的对于MySQL的支持(这主要体现在新的mysqli扩展中)为这种安全特征提供了强有力的支持(既有过程性的,也有面向对象特征的)。你可以从站点http://php.net/mysqli上获取有关mysqli的信息。注意,只有当你使用--with-mysqli=path/to/mysql_config选项编译PHP时,这种mysqli支持才可用。下面是该代码的一个过程性版本,用于保护一个基于mysqli的查询:
| <?php //检索用户的输入 $animalName = $_POST['animalName']; //连接到数据库 $connect = mysqli_connect( 'localhost', 'username', 'password', 'database' ); if ( !$connect ) exit( 'connection failed: ' . mysqli_connect_error() ); //创建一个查询语句源 $stmt = mysqli_prepare( $connect,"SELECT intelligence FROM animals WHERE name = ?" ); if ( $stmt ) { //把替代绑定到语句上 mysqli_stmt_bind_param( $stmt, "s", $animalName ); //执行该语句 mysqli_stmt_execute( $stmt ); //检索结果... mysqli_stmt_bind_result( $stmt, $intelligence ); // ...并显示它 if ( mysqli_stmt_fetch( $stmt ) ) { print "A $animalName has $intelligence intelligence.\n"; } else { print 'Sorry, no records found.'; } //清除语句源 mysqli_stmt_close( $stmt ); } mysqli_close( $connect ); ?> |
| <?php $animalName = $_POST['animalName']; $mysqli = new mysqli( 'localhost', 'username', 'password', 'database'); if ( !$mysqli ) exit( 'connection failed: ' . mysqli_connect_error() ); $stmt = $mysqli->prepare( "SELECT intelligence FROM animals WHERE name = ?" ); if ( $stmt ) { $stmt->bind_param( "s", $animalName ); $stmt->execute(); $stmt->bind_result( $intelligence ); if ( $stmt->fetch() ) { print "A $animalName has $intelligence intelligence.\n"; } else { print 'Sorry, no records found.'; } $stmt->close(); } $mysqli->close(); ?> |