SQL injection with PHP + SQLServer [duplicate]

5

How can I prevent SQL injection coming from an input via POST using PHP + SQLServer. (Using Microsoft SQL Server => mmsql)

I am doing the data abstraction of a DB that runs MYSQLI and in this case it is done this way.

$Email= mysqli_real_escape_string($conexao, $_POST['Email']);
$Senha= mysqli_real_escape_string($conexao, $_POST['Senha']); 
 
    
asked by anonymous 15.01.2016 / 20:49

1 answer

2

There are two drivers for connecting to the SQL Server PDO and SQLSRV, You have several questions about the PDO specific to SQL Server, from aa installation and configuration , connection creation and other aspects of the library .

Connection creation:

$servidor = 'ip ou servidor\instancia';
$db = 'test';
$usuario = 'user';
$senha = 'pass';        

$conexao = sqlsrv_connect($servidor, array('Database' => $db, 'UID' => $usuario, 'PWD' => $senha));

Escaping characters does not prevent or resolve the sql injection problem as shown this response , the best way to attack this problem is to filter the user inputs properly and use prepared statements.

For DML (insert, update or delete) make this code, this is just an example please do not store passwords in pure text format in the database.

$sql = "INSERT INTO usuarios(email, nome, senha) VALUES(?,?,?)";

$email = "[email protected]";
$nome = "Doge";
$senha = "wowsuchsecret";

$stmt = sqlsrv_prepare( $conexao, $sql, array($email, $nome, $senha));
if( !$stmt ) {
    die( print_r(sqlsrv_errors());
}

For selects:

$sql = "SELECT * FROM usuarios";
$stmt = sqlsrv_query($conexao, $sql);
if( $stmt === false) {
    die(print_r(sqlsrv_errors()));
}

while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
      echo $row['nome']." - ".$row['email']."<br />";
}
    
15.01.2016 / 21:32