如果插入用户输入而不修改SQL查询,则应用程序容易受到SQL注入的攻击,如下例所示:
$unsafe_variable = $_POST['user_input'];
mysql_query("INSERT INTO `table` (`column`) VALUES ('$unsafe_variable')");
Run Code Online (Sandbox Code Playgroud)
这是因为用户可以输入类似的内容value'); DROP TABLE table;--,查询变为:
INSERT INTO `table` (`column`) VALUES('value'); DROP TABLE table;--')
Run Code Online (Sandbox Code Playgroud)
可以采取哪些措施来防止这种情况发生?
警告:mysqli :: query():无法在第43行的C:\ Program Files(x86)\ EasyPHP-DevServer-13.1VC9\data\localweb\my portable files\class_EventCalendar.php中获取mysqli
以下是我的连接文件:
<?php
if(!isset($_SESSION))
{
session_start();
}
// Create array to hold error messages (if any)
$ErrorMsgs = array();
// Create new mysql connection object
$DBConnect = @new mysqli("localhost","root@localhost",
NULL,"Ladle");
// Check to see if connection errno data member is not 0 (indicating an error)
if ($DBConnect->connect_errno) {
// Add error to errors array
$ErrorMsgs[]="The database server is not available.".
" Connect Error is ".$DBConnect->connect_errno." ".
$DBConnect->connect_error.".";
}
?>
Run Code Online (Sandbox Code Playgroud)
这是我的班级:
<?php
class EventCalendar …Run Code Online (Sandbox Code Playgroud) 我有问题要建立一个连接到DB的代码,然后关闭连接.
我的DB类如下:
class DataBase {
private $conn;
private $info;
private $db;
public function __construct ($servername=DB_SERVER, $user=DB_USER, $pass=DB_PASS, $db=DB_DATABASE) {
$this->db = $db;
$this->conn = new mysqli($servername,$user,$pass, $this->db);
if (!$this->conn)
{
if ($this->conn->connect_error) {
$this->info = "ERROR CODE=DB100: Connection failed <br> " . $conn->connect_error;
$this->close();
echo $this->getInfo();
}
else {
$this->info = "ERROR CODE=DB101: Connection failed <br> ";
$this->close();
echo $this->getInfo();
}
}
}
public function getInfo () {
return $this->info;
}
// send sql to database
public function sendQuery ($sql, …Run Code Online (Sandbox Code Playgroud)